videoutil

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 13 Imported by: 0

README

videoutil

High-level Go wrapper around FFmpeg and FFprobe for video processing: transcoding, screenshot extraction, watermarking, and media probing.

The package is a pure library — no web framework, no job manager, no global state. All operations are context-aware (cancelable, timeout-able) and return explicit errors. Three API layers are provided: preset one-call helpers, a fluent command builder, and low-level FFmpeg/FFprobe execution with progress callbacks.

Key types

  • MediaInfo / VideoStream / AudioStream / StreamInfo — probed metadata
  • Progress — FFmpeg processing progress (frame, FPS, percent, done)
  • Position — overlay placement (PositionTopLeft, PositionCenter, PositionBottomRight, ...)
  • Command — fluent FFmpeg command builder

Preset functions

TranscodeMP4, Screenshot, AddImageWatermark, AddTextWatermark, Probe, and functional options like WithCRF, WithPreset, WithScreenshotSize, WithWatermarkPosition.

Quick start

import "github.com/LingByte/ling-base/common/videoutil"

err := videoutil.TranscodeMP4("input.mov", "output.mp4",
    videoutil.WithCRF(23), videoutil.WithPreset("medium"))

err = videoutil.Screenshot("input.mp4", "thumb.jpg", 10.0,
    videoutil.WithScreenshotSize(1280, 720))

info, err := videoutil.Probe("input.mp4")
fmt.Printf("Duration: %.1fs, Resolution: %dx%d\n",
    info.Duration.Seconds(), info.Video.Width, info.Video.Height)

Documentation

Overview

Package videoutil provides a high-level Go wrapper around FFmpeg and FFprobe for video processing tasks including transcoding, screenshot extraction, watermarking, and media probing.

Design

The package is a pure library — no web framework, no job manager, no global state. All operations are context-aware (cancelable, timeout- able) and return explicit errors.

Three layers of API are provided:

  1. **Preset functions** — one-call helpers for common tasks: TranscodeMP4, Screenshot, AddImageWatermark, AddTextWatermark, etc.

  2. **Command builder** — a fluent builder for custom FFmpeg commands: videoutil.NewCommand().Input("in.mp4").VideoCodec("libx264")...

  3. **FFmpeg/FFprobe tools** — low-level execution with progress callbacks, pipe support, and binary auto-detection.

Quick start

// Transcode to MP4 (H.264 + AAC)
err := videoutil.TranscodeMP4("input.mov", "output.mp4",
    videoutil.WithCRF(23), videoutil.WithPreset("medium"))

// Extract a screenshot at 10 seconds
err := videoutil.Screenshot("input.mp4", "thumb.jpg", 10.0,
    videoutil.WithScreenshotSize(1280, 720))

// Add an image watermark
err := videoutil.AddImageWatermark("input.mp4", "logo.png", "output.mp4",
    videoutil.WithWatermarkPosition(videoutil.PositionBottomRight))

// Probe media info
info, err := videoutil.Probe("input.mp4")
fmt.Printf("Duration: %.1fs, Resolution: %dx%d\n",
    info.Duration.Seconds(), info.Video.Width, info.Video.Height)

Index

Constants

This section is empty.

Variables

View Source
var DefaultFFmpeg = NewFFmpegTool()

DefaultFFmpeg is the default FFmpegTool used by package-level functions. Replace it with a custom tool if you need a specific binary path or timeout.

View Source
var DefaultFFprobe = NewFFprobeTool()

DefaultFFprobe is the default FFprobeTool used by package-level functions.

Functions

func AddImageWatermark

func AddImageWatermark(ctx context.Context, input, watermark, output string, opts ...WatermarkOption) error

AddImageWatermark overlays an image watermark onto a video.

func AddTextWatermark

func AddTextWatermark(ctx context.Context, input, output, text string, fontFile string, opts ...WatermarkOption) error

AddTextWatermark overlays text onto a video using the drawtext filter.

func BuildImageWatermarkFilter

func BuildImageWatermarkFilter(opts WatermarkOptions) string

BuildImageWatermarkFilter builds the filter_complex string for overlaying an image watermark onto a video.

Input 0 is the main video, input 1 is the watermark image. The output label is "[out]".

func BuildTextWatermarkFilter

func BuildTextWatermarkFilter(text, fontFile string, fontSize int, color string, opts WatermarkOptions) string

BuildTextWatermarkFilter builds the filter_complex string for overlaying text onto a video using the drawtext filter.

Parameters:

  • text: the text to display
  • fontFile: path to a .ttf/.otf font file (may be empty for default font)
  • fontSize: font size in pixels (default: 24)
  • color: font color (default: "white")
  • opts: position, margin, opacity

func Clip

func Clip(ctx context.Context, input, output string, opts ...ClipOption) error

Clip extracts a segment from a video file.

func Concat

func Concat(ctx context.Context, inputs []string, output string) error

Concat concatenates multiple video files into one. All files should have the same codec and resolution. Uses the concat demuxer.

func CreateGIF

func CreateGIF(ctx context.Context, input, output string, opts ...GIFOption) error

CreateGIF creates an animated GIF from a video segment.

func ExtractAudio

func ExtractAudio(ctx context.Context, input, output string, codec string, bitrate string) error

ExtractAudio extracts the audio track from a video file.

func OverlayExpr

func OverlayExpr(pos Position, margin int) (xExpr, yExpr string)

OverlayExpr returns FFmpeg overlay=x:y expressions for the given position. Uses W/H (overlay width/height) and w/h (main width/height) variables available in the overlay filter.

func OverlayPosition

func OverlayPosition(pos Position, videoW, videoH, overlayW, overlayH, margin int) (x, y int)

OverlayPosition returns the x:y coordinates for placing an overlay at the given position with optional margin.

func Remux

func Remux(ctx context.Context, input, output string) error

Remux changes the container format without re-encoding (stream copy).

func Screenshot

func Screenshot(ctx context.Context, input, output string, atSeconds float64, opts ...ScreenshotOption) error

Screenshot extracts a single frame from a video at the given timestamp.

func Transcode

func Transcode(ctx context.Context, input, output string, opts ...TranscodeOption) error

Transcode transcodes a video file with the given options. It uses a default FFmpegTool; pass nil for opts to use defaults.

func TranscodeMP4

func TranscodeMP4(input, output string, opts ...TranscodeOption) error

TranscodeMP4 is a convenience wrapper that transcodes to MP4 (H.264 + AAC).

func TranscodeWithProgress

func TranscodeWithProgress(ctx context.Context, input, output string, onProgress func(Progress), opts ...TranscodeOption) error

TranscodeWithProgress is like Transcode but reports progress. The total duration is probed automatically to compute Percent.

Types

type AudioStream

type AudioStream struct {
	Index         int               `json:"index"`
	Codec         string            `json:"codec"` // e.g. "aac", "mp3"
	Profile       string            `json:"profile"`
	SampleRate    int               `json:"sampleRate"` // Hz
	Channels      int               `json:"channels"`
	ChannelLayout string            `json:"channelLayout"` // e.g. "stereo", "mono"
	BitRate       int64             `json:"bitRate"`
	Duration      time.Duration     `json:"duration"`
	Tags          map[string]string `json:"tags"`
}

AudioStream holds metadata about an audio stream.

type ClipOption

type ClipOption func(*ClipOptions)

ClipOption is a functional option for ClipOptions.

func WithClipCopy

func WithClipCopy() ClipOption

WithClipCopy uses stream copy (no re-encoding).

func WithClipDuration

func WithClipDuration(seconds float64) ClipOption

WithClipDuration sets the clip duration.

func WithClipEnd

func WithClipEnd(seconds float64) ClipOption

WithClipEnd sets the clip end time.

func WithClipStart

func WithClipStart(seconds float64) ClipOption

WithClipStart sets the clip start time.

type ClipOptions

type ClipOptions struct {
	Start    float64 // start time in seconds (default: 0)
	End      float64 // end time in seconds (0 = until end)
	Duration float64 // duration in seconds (overrides End if set)
	Copy     bool    // if true, stream copy (no re-encoding, faster but less precise)
}

ClipOptions configures a clip extraction.

type Command

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

Command is a fluent builder for FFmpeg command-line arguments. It does NOT execute anything — use FFmpegTool.Run to execute.

func NewCommand

func NewCommand() *Command

NewCommand creates a new FFmpeg command with -y (overwrite) and -hide_banner as defaults.

func (*Command) Append

func (c *Command) Append(args ...string) *Command

Append adds raw arguments. Returns c for chaining.

func (*Command) Args

func (c *Command) Args() []string

Args returns a copy of the accumulated arguments.

func (*Command) AudioBitRate

func (c *Command) AudioBitRate(bitrate string) *Command

AudioBitRate sets the audio bitrate (e.g. "128k", "192k").

func (*Command) AudioChannels

func (c *Command) AudioChannels(n int) *Command

AudioChannels sets the number of audio channels (1=mono, 2=stereo).

func (*Command) AudioCodec

func (c *Command) AudioCodec(codec string) *Command

AudioCodec sets the audio codec (e.g. "aac", "mp3", "copy").

func (*Command) AudioFilter

func (c *Command) AudioFilter(filter string) *Command

AudioFilter sets the audio filter chain.

func (*Command) AudioSampleRate

func (c *Command) AudioSampleRate(hz int) *Command

AudioSampleRate sets the audio sample rate (e.g. 44100, 48000).

func (*Command) CRF

func (c *Command) CRF(value int) *Command

CRF sets the Constant Rate Factor (quality) for x264/x265. Typical range: 0-51, lower = higher quality (18-28 is common).

func (*Command) CopyAudio

func (c *Command) CopyAudio() *Command

CopyAudio copies the audio stream without re-encoding.

func (*Command) CopyVideo

func (c *Command) CopyVideo() *Command

CopyVideo copies the video stream without re-encoding.

func (*Command) Duration

func (c *Command) Duration(seconds float64) *Command

Duration limits the duration of the input (after -ss).

func (*Command) Frames

func (c *Command) Frames(n int) *Command

Frames limits the number of output video frames (useful for screenshots).

func (*Command) Input

func (c *Command) Input(path string) *Command

Input adds an input file. Can be called multiple times for multiple inputs.

func (*Command) InputFormat

func (c *Command) InputFormat(format string) *Command

InputFormat sets the input format (e.g. "mp4", "flv").

func (*Command) LogLevel

func (c *Command) LogLevel(level string) *Command

LogLevel sets the log level: "quiet", "error", "warning", "info", etc.

func (*Command) Map

func (c *Command) Map(spec string) *Command

Map maps an input stream to output (e.g. "0:v:0", "0:a:0").

func (*Command) MaxKeyInterval

func (c *Command) MaxKeyInterval(frames int) *Command

MaxKeyInterval sets the maximum keyframe interval (GOP size).

func (*Command) MovFlagsFastStart

func (c *Command) MovFlagsFastStart() *Command

MovFlagsFastStart moves the moov atom to the beginning for fast streaming.

func (*Command) NoAudio

func (c *Command) NoAudio() *Command

NoAudio drops the audio stream (video-only output).

func (*Command) NoVideo

func (c *Command) NoVideo() *Command

NoVideo drops the video stream (audio-only output).

func (*Command) Output

func (c *Command) Output(path string) *Command

Output sets the output file path.

func (*Command) OutputFormat

func (c *Command) OutputFormat(format string) *Command

OutputFormat sets the output container format.

func (*Command) Overwrite

func (c *Command) Overwrite(on bool) *Command

Overwrite sets whether to overwrite output files. Default is true.

func (*Command) PixelFormat

func (c *Command) PixelFormat(format string) *Command

PixelFormat sets the output pixel format (e.g. "yuv420p").

func (*Command) Preset

func (c *Command) Preset(preset string) *Command

Preset sets the encoding preset (e.g. "ultrafast", "fast", "medium", "slow").

func (*Command) Scale

func (c *Command) Scale(width, height int) *Command

Scale adds a scale filter to the video filter chain.

func (*Command) ScaleKeepAspect

func (c *Command) ScaleKeepAspect(width, height int) *Command

ScaleKeepAspect scales to fit within width x height while keeping aspect ratio (no padding).

func (*Command) ScalePad

func (c *Command) ScalePad(width, height int) *Command

ScalePad scales to width x height, padding with black to maintain aspect.

func (*Command) SeekTo

func (c *Command) SeekTo(seconds float64) *Command

SeekTo seeks to the given position before reading input (fast seek). Place before Input() for fast seeking, or after for accurate seeking.

func (*Command) String

func (c *Command) String() string

String returns the full command as a space-joined string (for logging).

func (*Command) Tune

func (c *Command) Tune(tune string) *Command

Tune sets the tuning (e.g. "film", "animation", "stillimage", "fastdecode").

func (*Command) VideoBitRate

func (c *Command) VideoBitRate(bitrate string) *Command

VideoBitRate sets the video bitrate (e.g. "2M", "500k").

func (*Command) VideoCodec

func (c *Command) VideoCodec(codec string) *Command

VideoCodec sets the video codec (e.g. "libx264", "libx265", "copy").

func (*Command) VideoFilter

func (c *Command) VideoFilter(filter string) *Command

VideoFilter sets the video filter chain (e.g. "scale=1280:720").

func (*Command) VideoFilterComplex

func (c *Command) VideoFilterComplex(filter string) *Command

VideoFilterComplex sets a complex filter graph.

func (*Command) VideoFrameRate

func (c *Command) VideoFrameRate(fps string) *Command

VideoFrameRate sets the output frame rate (e.g. "30", "30000/1001").

type FFmpegTool

type FFmpegTool struct {
	BinaryPath string        // path to ffmpeg; "" means auto-detect via PATH
	Timeout    time.Duration // default 0 = no timeout (caller controls via ctx)
	// contains filtered or unexported fields
}

FFmpegTool wraps the FFmpeg binary, caching its resolved path and version. It is safe for concurrent use.

func NewFFmpegTool

func NewFFmpegTool() *FFmpegTool

NewFFmpegTool creates a new FFmpeg tool with default settings. BinaryPath defaults to "ffmpeg" (auto-detected via PATH).

func NewFFmpegToolWithPath

func NewFFmpegToolWithPath(path string) *FFmpegTool

NewFFmpegToolWithPath creates a tool using an explicit binary path.

func (*FFmpegTool) AddImageWatermark

func (t *FFmpegTool) AddImageWatermark(ctx context.Context, input, watermark, output string, opts ...WatermarkOption) error

AddImageWatermark overlays an image watermark using this FFmpeg tool.

func (*FFmpegTool) AddTextWatermark

func (t *FFmpegTool) AddTextWatermark(ctx context.Context, input, output, text, fontFile string, opts ...WatermarkOption) error

AddTextWatermark overlays text using this FFmpeg tool.

func (*FFmpegTool) Clip

func (t *FFmpegTool) Clip(ctx context.Context, input, output string, opts ...ClipOption) error

Clip extracts a segment using this FFmpeg tool.

func (*FFmpegTool) Concat

func (t *FFmpegTool) Concat(ctx context.Context, inputs []string, output string) error

Concat concatenates multiple video files using this FFmpeg tool.

func (*FFmpegTool) CreateGIF

func (t *FFmpegTool) CreateGIF(ctx context.Context, input, output string, opts ...GIFOption) error

CreateGIF creates an animated GIF using this FFmpeg tool.

func (*FFmpegTool) ExtractAudio

func (t *FFmpegTool) ExtractAudio(ctx context.Context, input, output, codec, bitrate string) error

ExtractAudio extracts the audio track using this FFmpeg tool.

func (*FFmpegTool) Remux

func (t *FFmpegTool) Remux(ctx context.Context, input, output string) error

Remux changes the container format using this FFmpeg tool.

func (*FFmpegTool) ResolvedPath

func (t *FFmpegTool) ResolvedPath() string

ResolvedPath returns the absolute path to the FFmpeg binary after detection. Returns "" if ensureReady has not been called.

func (*FFmpegTool) Run

func (t *FFmpegTool) Run(ctx context.Context, args []string, onProgress func(Progress)) error

Run executes an FFmpeg command. If onProgress is non-nil, progress events are reported via the callback (the -progress pipe:1 flag is automatically appended).

func (*FFmpegTool) RunWithProgress

func (t *FFmpegTool) RunWithProgress(ctx context.Context, args []string, onProgress func(Progress)) (Progress, error)

RunWithProgress is like Run but also returns the last progress event.

func (*FFmpegTool) Screenshot

func (t *FFmpegTool) Screenshot(ctx context.Context, input, output string, atSeconds float64, opts ...ScreenshotOption) error

Screenshot extracts a single frame using this FFmpeg tool.

func (*FFmpegTool) Transcode

func (t *FFmpegTool) Transcode(ctx context.Context, input, output string, opts ...TranscodeOption) error

Transcode transcodes a video file using this FFmpeg tool instance.

func (*FFmpegTool) TranscodeWithProgress

func (t *FFmpegTool) TranscodeWithProgress(ctx context.Context, input, output string, onProgress func(Progress), opts ...TranscodeOption) error

TranscodeWithProgress transcodes with progress reporting.

func (*FFmpegTool) Version

func (t *FFmpegTool) Version(ctx context.Context) (string, error)

Version returns the detected FFmpeg version string.

type FFprobeTool

type FFprobeTool struct {
	BinaryPath string        // path to ffprobe; "" means auto-detect
	Timeout    time.Duration // default 15s
	// contains filtered or unexported fields
}

FFprobeTool wraps the FFprobe binary, caching its resolved path and version. It is safe for concurrent use.

func NewFFprobeTool

func NewFFprobeTool() *FFprobeTool

NewFFprobeTool creates a new FFprobe tool with default settings.

func NewFFprobeToolWithPath

func NewFFprobeToolWithPath(path string) *FFprobeTool

NewFFprobeToolWithPath creates a tool using an explicit binary path.

func (*FFprobeTool) Probe

func (t *FFprobeTool) Probe(ctx context.Context, input string) (*MediaInfo, error)

Probe executes ffprobe and returns a high-level MediaInfo struct.

func (*FFprobeTool) ProbeRaw

func (t *FFprobeTool) ProbeRaw(ctx context.Context, input string) (*ffprobeJSON, error)

ProbeRaw executes ffprobe and returns the raw JSON output.

func (*FFprobeTool) Version

func (t *FFprobeTool) Version(ctx context.Context) (string, error)

Version returns the detected FFprobe version string.

type FilterGraph

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

FilterGraph builds a complex FFmpeg filter graph string. It is used for operations that require multiple inputs (e.g. overlaying a watermark image onto a video).

func NewFilterGraph

func NewFilterGraph() *FilterGraph

NewFilterGraph creates a new empty filter graph.

func (*FilterGraph) AddChain

func (g *FilterGraph) AddChain(chain string) *FilterGraph

AddChain adds a filter chain (a series of filters separated by commas). Each chain can have input/output labels via [label] syntax.

func (*FilterGraph) String

func (g *FilterGraph) String() string

String returns the complete filter graph string for -filter_complex.

type GIFOption

type GIFOption func(*GIFOptions)

GIFOption is a functional option for GIFOptions.

func WithGIFDuration

func WithGIFDuration(seconds float64) GIFOption

WithGIFDuration sets the GIF duration.

func WithGIFFPS

func WithGIFFPS(fps int) GIFOption

WithGIFFPS sets the GIF frame rate.

func WithGIFOptimize

func WithGIFOptimize() GIFOption

WithGIFOptimize enables palette optimization for better quality.

func WithGIFSize

func WithGIFSize(width, height int) GIFOption

WithGIFSize sets the GIF dimensions.

func WithGIFStart

func WithGIFStart(seconds float64) GIFOption

WithGIFStart sets the GIF start time.

type GIFOptions

type GIFOptions struct {
	Start    float64 // start time in seconds (default: 0)
	Duration float64 // duration in seconds (default: 3)
	Width    int     // 0 = original width
	Height   int     // 0 = original height
	FPS      int     // frames per second (default: 10)
	Optimize bool    // if true, use palettegen + paletteuse for better quality
}

GIFOptions configures GIF creation from a video.

func DefaultGIFOptions

func DefaultGIFOptions() GIFOptions

DefaultGIFOptions returns sensible defaults.

type MediaInfo

type MediaInfo struct {
	Filename string            `json:"filename"`
	Format   string            `json:"format"`   // container format (e.g. "mp4")
	Duration time.Duration     `json:"duration"` // total duration
	Size     int64             `json:"size"`     // file size in bytes
	BitRate  int64             `json:"bitRate"`  // overall bitrate (bps)
	Video    *VideoStream      `json:"video"`    // first video stream (nil if none)
	Audio    *AudioStream      `json:"audio"`    // first audio stream (nil if none)
	Streams  []StreamInfo      `json:"streams"`  // all streams
	Tags     map[string]string `json:"tags"`     // format-level tags
}

MediaInfo holds probed metadata about a media file.

func Probe

func Probe(ctx context.Context, input string) (*MediaInfo, error)

Probe probes a media file and returns its metadata. It uses the default FFprobeTool.

func ProbeFile

func ProbeFile(input string) (*MediaInfo, error)

ProbeFile is a convenience wrapper that creates a background context.

type Position

type Position int

Position specifies where to place an overlay (watermark, logo, etc.) on the video frame.

const (
	PositionTopLeft     Position = iota // top-left corner
	PositionTopRight                    // top-right corner
	PositionBottomLeft                  // bottom-left corner
	PositionBottomRight                 // bottom-right corner
	PositionCenter                      // center of the frame
)

type Progress

type Progress struct {
	Frame   int           `json:"frame"`   // total frames processed
	FPS     float64       `json:"fps"`     // processing speed in frames/sec
	BitRate string        `json:"bitRate"` // current output bitrate
	Speed   string        `json:"speed"`   // processing speed (e.g. "1.5x")
	OutTime time.Duration `json:"outTime"` // output time
	Done    bool          `json:"done"`    // whether processing is complete
	// Percent is an estimate of completion (0-100), computed from
	// OutTime and the total duration if known. 0 if unknown.
	Percent float64 `json:"percent"`
	// Extra holds any unrecognized progress fields.
	Extra map[string]string `json:"extra,omitempty"`
}

Progress represents FFmpeg processing progress, reported via the -progress pipe:1 output.

type ScreenshotOption

type ScreenshotOption func(*ScreenshotOptions)

ScreenshotOption is a functional option for ScreenshotOptions.

func WithExactSeek

func WithExactSeek() ScreenshotOption

WithExactSeek uses accurate seeking (slower but frame-accurate).

func WithScreenshotFormat

func WithScreenshotFormat(format string) ScreenshotOption

WithScreenshotFormat sets the output format ("jpg" or "png").

func WithScreenshotQuality

func WithScreenshotQuality(q int) ScreenshotOption

WithScreenshotQuality sets the JPEG quality (2-31, lower = better).

func WithScreenshotSize

func WithScreenshotSize(width, height int) ScreenshotOption

WithScreenshotSize sets the screenshot dimensions.

type ScreenshotOptions

type ScreenshotOptions struct {
	Width     int    // 0 = original width
	Height    int    // 0 = original height
	Format    string // "jpg" (default) or "png"
	Quality   int    // JPEG quality 2-31 (lower = better, default 2)
	ExactSeek bool   // if true, seeks after -i (accurate but slower)
}

ScreenshotOptions configures screenshot extraction.

func DefaultScreenshotOptions

func DefaultScreenshotOptions() ScreenshotOptions

DefaultScreenshotOptions returns sensible defaults.

type StreamInfo

type StreamInfo struct {
	Index      int               `json:"index"`
	Codec      string            `json:"codec"`
	CodecType  string            `json:"codecType"` // "video", "audio", "subtitle", etc.
	CodecLong  string            `json:"codecLong"`
	Width      int               `json:"width"`
	Height     int               `json:"height"`
	SampleRate int               `json:"sampleRate"`
	Channels   int               `json:"channels"`
	Duration   string            `json:"duration"`
	Tags       map[string]string `json:"tags"`
}

StreamInfo holds metadata about any stream (video, audio, subtitle, etc.).

type TranscodeOption

type TranscodeOption func(*TranscodeOptions)

TranscodeOption is a functional option for TranscodeOptions.

func WithAudioBitRate

func WithAudioBitRate(br string) TranscodeOption

WithAudioBitRate sets the audio bitrate.

func WithAudioChannels

func WithAudioChannels(n int) TranscodeOption

WithAudioChannels sets the number of audio channels.

func WithAudioCodec

func WithAudioCodec(codec string) TranscodeOption

WithAudioCodec sets the audio codec.

func WithCRF

func WithCRF(crf int) TranscodeOption

WithCRF sets the CRF (quality) value.

func WithFastStart

func WithFastStart() TranscodeOption

WithFastStart enables MP4 faststart.

func WithFrameRate

func WithFrameRate(fps string) TranscodeOption

WithFrameRate sets the output frame rate.

func WithNoAudio

func WithNoAudio() TranscodeOption

WithNoAudio drops the audio stream.

func WithNoVideo

func WithNoVideo() TranscodeOption

WithNoVideo drops the video stream (audio-only output).

func WithPad

func WithPad(width, height int) TranscodeOption

WithPad sets the output resolution with padding.

func WithPixelFormat

func WithPixelFormat(pf string) TranscodeOption

WithPixelFormat sets the output pixel format.

func WithPreset

func WithPreset(preset string) TranscodeOption

WithPreset sets the encoding preset.

func WithSampleRate

func WithSampleRate(hz int) TranscodeOption

WithSampleRate sets the audio sample rate.

func WithScale

func WithScale(width, height int) TranscodeOption

WithScale sets the output resolution.

func WithTune

func WithTune(tune string) TranscodeOption

WithTune sets the encoding tune.

func WithVideoBitRate

func WithVideoBitRate(br string) TranscodeOption

WithVideoBitRate sets the video bitrate (overrides CRF).

func WithVideoCodec

func WithVideoCodec(codec string) TranscodeOption

WithVideoCodec sets the video codec.

type TranscodeOptions

type TranscodeOptions struct {
	VideoCodec    string // default "libx264"
	AudioCodec    string // default "aac"
	CRF           int    // 0 = use default (23)
	Preset        string // default "medium"
	Tune          string // e.g. "film", "animation"; "" = none
	ScaleWidth    int    // 0 = no scaling
	ScaleHeight   int    // 0 = keep aspect
	PadToSize     bool   // if true, pad with black bars to exact ScaleWidth x ScaleHeight
	FrameRate     string // e.g. "30"; "" = keep original
	PixelFormat   string // default "yuv420p"
	VideoBitRate  string // e.g. "2M"; "" = use CRF
	AudioBitRate  string // e.g. "128k"; "" = default
	SampleRate    int    // 0 = keep original
	AudioChannels int    // 0 = keep original
	FastStart     bool   // default true (for MP4)
	NoAudio       bool   // drop audio
	NoVideo       bool   // drop video (audio only)
}

TranscodeOptions configures a transcoding operation.

func DefaultTranscodeOptions

func DefaultTranscodeOptions() TranscodeOptions

DefaultTranscodeOptions returns sensible defaults for H.264/AAC MP4.

type VideoStream

type VideoStream struct {
	Index       int               `json:"index"`
	Codec       string            `json:"codec"` // e.g. "h264", "hevc"
	Profile     string            `json:"profile"`
	Width       int               `json:"width"`
	Height      int               `json:"height"`
	PixelFormat string            `json:"pixelFormat"`
	FPS         float64           `json:"fps"`     // frames per second
	BitRate     int64             `json:"bitRate"` // video bitrate (bps, 0 if unknown)
	Duration    time.Duration     `json:"duration"`
	IsHDR       bool              `json:"isHdr"`
	Tags        map[string]string `json:"tags"`
}

VideoStream holds metadata about a video stream.

type WatermarkOption

type WatermarkOption func(*WatermarkOptions)

WatermarkOption is a functional option for watermark operations.

func WithWatermarkMargin

func WithWatermarkMargin(margin int) WatermarkOption

WithWatermarkMargin sets the watermark margin in pixels.

func WithWatermarkOpacity

func WithWatermarkOpacity(opacity float64) WatermarkOption

WithWatermarkOpacity sets the watermark opacity (0.0-1.0).

func WithWatermarkPosition

func WithWatermarkPosition(pos Position) WatermarkOption

WithWatermarkPosition sets the watermark position.

func WithWatermarkScale

func WithWatermarkScale(scale float64) WatermarkOption

WithWatermarkScale sets the watermark scale factor (relative to video width).

type WatermarkOptions

type WatermarkOptions struct {
	Position Position // corner/center (default: bottom-right)
	Margin   int      // pixel margin from edge (default: 10)
	Scale    float64  // scale factor relative to video width (0 = no scaling, default: 0)
	Opacity  float64  // 0.0-1.0, 1 = fully opaque (default: 1)
}

WatermarkOptions configures how a watermark is applied.

func DefaultWatermarkOptions

func DefaultWatermarkOptions() WatermarkOptions

DefaultWatermarkOptions returns sensible defaults.

Jump to

Keyboard shortcuts

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