ffthumbs

package module
v0.0.0-...-5a7cdbc Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2023 License: MIT Imports: 20 Imported by: 0

README

ffthumbs

Golang FFmpeg thumbnails generator

Requirements

  • FFmpeg >= 5.0.0
  • Go >= 1.21.0

Supported thumbnails format

  • Simple thumbnails (OutputTypeThumbs)
  • Sprites (each sprite contains multiple thumbs - tiles) (OutputTypeSprites)

Supported scale operations

  • Scale to fixed resolution (set width and height to fixed numbers)
    • Fill to fit into fixed resolution aspect ratio (ScaleBehaviorFillToKeepAspectRatio)
    • Crop to fit into fixed resolution (ScaleBehaviorCropToFit)
  • Automatically scale to preserve original media aspect ratio (set width or height to -1)

For more options see config.go

This package is goroutine-safe (could be used with an unlimited number of concurrent calls).

Examples

Documentation

Index

Constants

View Source
const (
	// DefaultFilename is an output default filename
	DefaultFilename = "%04d.jpg"
)

Variables

This section is empty.

Functions

func BuildComplexFilters

func BuildComplexFilters(outputs []*OutputConfig) (string, error)

BuildComplexFilters builds ffmpeg -filter_complex arg based on provided outputs config, on fail it returns ValidationError

func BuildHeadersStr

func BuildHeadersStr(headers map[string]string) string

func FindFfmpeg

func FindFfmpeg() (string, error)

FindFfmpeg finds path to ffmpeg in OS $PATH path variable

func FindProbe

func FindProbe() (string, error)

FindProbe finds path to ffprobe in OS $PATH path variable

func GetFfmpegVersion

func GetFfmpegVersion(ffmpegPath string) (*version.Version, error)

GetFfmpegVersion returns ffmpeg version number, e.g. 6.0 or 5.3.1

func IsSameOutputConfigFilters

func IsSameOutputConfigFilters(c1, c2 *OutputConfig) bool

func IsSameScaleConfig

func IsSameScaleConfig(c1, c2 *ScaleConfig) bool

IsSameScaleConfig check is two scale configurations equal

func VerifyFfmpegVersion

func VerifyFfmpegVersion(ffmpegPath string) error

VerifyFfmpegVersion verifies that the provided ffmpeg binary meets the minimal version requirement

Types

type Config

type Config struct {
	// FfmpegPath path to ffmpeg binary, default: search binary in OS $PATH variable
	FfmpegPath string
	// Concurrency limit amount of concurrent thumbnails generation, default: 2
	Concurrency int
	// Headers configures which headers should pass ffmpeg if requested file is a network url
	Headers map[string]string
	// Outputs configure outputs of snapshots (thumbs)
	Outputs []*OutputConfig
	// Logger set pre-configured logger if you have one, default: json logger to stdout with debug log level
	Logger *slog.Logger
	// DisableProgressLogs ffmpeg's progress logs
	DisableProgressLogs bool
	// contains filtered or unexported fields
}

type GenerateRequest

type GenerateRequest struct {

	// MediaURL path to media file (can be either a network path or a local fs path)
	MediaURL string

	// OutputDst allows to override OutputConfig.DstPath
	// map format is an output index => dest path
	OutputDst map[int]string

	// Context is used to cancel command
	Context context.Context

	// DoneChan channel to receive request processing result
	DoneChan chan *GenerateResult

	// LogArgs is an additional log args that will be appended to logs
	LogArgs []slog.Attr
	// contains filtered or unexported fields
}

func (*GenerateRequest) GetId

func (r *GenerateRequest) GetId() uint64

GetId returns request id for better async processing, i.e. user could identify what request was processed

type GenerateResult

type GenerateResult struct {
	// Req is a processed request
	Req *GenerateRequest
	// Err is an error during Req processing
	Err error
	// Duration measures how much time was spent to process Req
	Duration time.Duration
}

type Generator

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

func NewGenerator

func NewGenerator(cfg *Config) (*Generator, error)

NewGenerator constructs new Generator based on provided config

func (*Generator) Generate

func (g *Generator) Generate(req *GenerateRequest) error

Generate is a blocking thumbnails generation, if you want to go async see GenerateAsync

func (*Generator) GenerateAsync

func (g *Generator) GenerateAsync(req *GenerateRequest) error

GenerateAsync is an asynchronous thumbnails generation using the underlying goroutine pool. Concurrency is limited by Config.Concurrency. When all goroutines in pool are busy this method would block until a free goroutine is available.

Each request passed to this method will get unique identifier, you can get it by calling GenerateRequest.GetId().

func (*Generator) GetConcurrency

func (g *Generator) GetConcurrency() int

GetConcurrency returns current concurrency setting

func (*Generator) SetConcurrency

func (g *Generator) SetConcurrency(newConcurrency int)

SetConcurrency sets current concurrency number, new concurrency should be a positive int, otherwise value 2 will be used

func (*Generator) Wait

func (g *Generator) Wait()

Wait waits until all requests processed

type OutputConfig

type OutputConfig struct {

	// DstPath sets thumbs output path, default: app work dir + DefaultFilename
	// can be overridden in GenerateRequest.OutputDst
	DstPath string

	// Scale configure scaling behavior
	Scale ScaleConfig

	// SnapshotInterval indicates how often to make screenshots from video
	SnapshotInterval time.Duration

	// Type configures output type, e.g. sprites or thumbs
	Type OutputType

	// Sprites configures output sprites behavior when Type is set to OutputTypeSprites
	Sprites SpritesConfig

	// Quality configures quality level (0 = default, valid values are 1-31, lower is better)
	// See: https://ffmpeg.org/ffmpeg-codecs.html#Options-21 (q:v option)
	Quality int
	// contains filtered or unexported fields
}

func (*OutputConfig) EqFilters

func (c *OutputConfig) EqFilters(cfg *OutputConfig) bool

type OutputType

type OutputType int

OutputType configures output type, e.g. spites or thumbs

const (
	// OutputTypeThumbs output thumbnail for each OutputConfig.SnapshotInterval
	OutputTypeThumbs OutputType = iota
	// OutputTypeSprites output sprite for each OutputConfig.SnapshotInterval respecting OutputConfig.Sprites
	OutputTypeSprites
)

type ScaleBehavior

type ScaleBehavior int

ScaleBehavior configures how scaling will be performed See: https://superuser.com/questions/547296/resizing-videos-with-ffmpeg-avconv-to-fit-into-static-sized-player/1136305#1136305

const (
	// ScaleBehaviorNone do not attempt to change scaling behavior
	ScaleBehaviorNone ScaleBehavior = iota
	// ScaleBehaviorFillToKeepAspectRatio is useful when you want to resize to fixed resolution
	// (width and height must be set to fixed size), but preserve original aspect ratio.
	// Letterboxing will occur instead of pillarboxing if the input aspect ratio
	// is wider than the output aspect ratio.
	// For example, an input with a 2.35:1 aspect ratio fit into a 16:9 output will result in letterboxing.
	ScaleBehaviorFillToKeepAspectRatio
	// ScaleBehaviorCropToFit is useful when you want to resize to fixed resolution
	// (width and height must be set to fixed size), but preserve fixed size by
	// cropping frame to fit into target resolution.
	ScaleBehaviorCropToFit
)

type ScaleConfig

type ScaleConfig struct {
	// Width is an outgoing width resolution, could be -1 to resize by Height respecting aspect ratio
	Width int
	// Height is an outgoing height resolution, could be -1 to resize by Width respecting aspect ratio
	Height int
	// Behavior is configuring how scaling will be performed
	Behavior ScaleBehavior
}

ScaleConfig is an output files resolution config

func (*ScaleConfig) Eq

func (c *ScaleConfig) Eq(cfg *ScaleConfig) bool

Eq is ScaleConfig equal to another scale config

func (*ScaleConfig) IsFixedResolution

func (c *ScaleConfig) IsFixedResolution() bool

type ScreenGenerator

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

func NewScreensGenerator

func NewScreensGenerator(cfg *ScreensConfig) (*ScreenGenerator, error)

NewScreensGenerator constructs new ScreenGenerator based on provided config

func (*ScreenGenerator) Generate

func (g *ScreenGenerator) Generate(req *ScreenshotsRequest) error

type ScreensConfig

type ScreensConfig struct {
	// FfmpegPath path to ffmpeg binary, default: search binary in OS $PATH variable
	FfmpegPath  string
	FfprobePath string

	// Headers configures which headers should pass ffmpeg if requested file is a network url
	Headers map[string]string
	// Logger set pre-configured logger if you have one, default: json logger to stdout with debug log level
	Logger *slog.Logger
	// contains filtered or unexported fields
}

type ScreenshotsRequest

type ScreenshotsRequest struct {
	// MediaURL is a path to media file
	MediaURL string

	Scale *ScaleConfig

	// ThumbsNo is total count of screenshots
	ThumbsNo int

	// TimeUnits make screenshots by provided time uints instead of ThumbsNo
	TimeUnits []TimeUnit

	OutputDst string

	// Context is used to cancel command
	Context context.Context

	// LogArgs is an additional log launchParams that will be appended to logs
	LogArgs []slog.Attr
}

type SpriteDimensions

type SpriteDimensions struct {
	Columns int
	Rows    int
}

SpriteDimensions configure how many tiles and how tiles will be placed in an output file

type SpritesConfig

type SpritesConfig struct {
	// Dimensions is an output grid size,
	// configure how many tiles and how tiles will be placed in an output file
	Dimensions SpriteDimensions
}

SpritesConfig is a sprites output configuration

type TimeUnit

type TimeUnit struct {
	Type TimeUnitType
	// Value time point in seconds or percent of media duration
	Value float64
}

type TimeUnitType

type TimeUnitType int
const (
	TimeUnitTypePoint TimeUnitType = iota
	TimeUnitTypePercent
)

type ValidationErrType

type ValidationErrType int
const (
	ValidationErrTypeNoOutputs ValidationErrType = iota
	ValidationErrTypeQuality
	ValidationErrTypeSnapshotInterval
	ValidationErrTypeOutputType
	ValidationErrTypeScale
	ValidationErrTypeSpiteDims
	ValidationErrTypeScaleBehavior
)

type ValidationError

type ValidationError struct {
	Type ValidationErrType
	Msg  string
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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