ffmpeg

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2023 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OutputTypeImage        = 1 // Output as image
	OutputTypeAudioSegment = 2 // Output as audio segment
)
View Source
const (
	CaptureModeByInterval = iota // Capture by duration (every n seconds), default value
	CaptureModeByFrame           // Capture by every n frame
)
View Source
const (
	DefaultIOTimeout = 2 // Default to 2 seconds
)

Variables

View Source
var (
	ErrInvalidUrl            = fmt.Errorf("INVALID_URL")              // Not a valid url, 5xx or 400
	ErrUrlExpiredOrForbidden = fmt.Errorf("URL_EXPIRED_OR_FORBIDDEN") // Url expired or forbidden (403)
	ErrUrlNotFound           = fmt.Errorf("URL_NOT_FOUND")            // Url not found (404)
	ErrMediaServerError      = fmt.Errorf("MEDIA_SERVER_ERROR")       // Media server returned 5xx response
	ErrInvalidData           = fmt.Errorf("INVALID_DATA")             // Invalid data
	ErrResolveHostFailed     = fmt.Errorf("RESOLVE_HOST_FAILED")      // Failed to resolve hostname
	ErrConnectionTimeout     = fmt.Errorf("CONNECTION_TIMEOUT")       // Connection timeout
	ErrOOMKilled             = fmt.Errorf("OOM_KILLED")               // OOM killed
	ErrNoStream              = fmt.Errorf("NO_STREAM")                // No stream/does not contain any stream
	ErrStreamClosed          = fmt.Errorf("STREAM_CLOSED")            // Stream closed. This may be a normal result instead of a REAL ERROR
)
View Source
var SEIRegex, _ = regexp.Compile(`{".+([0-9]|}|]|")}`)

Functions

func ParseCaptureCommand

func ParseCaptureCommand(opt *CaptureOptions) string

ParseCaptureCommand parses capture command string

func ParseCaptureOptions

func ParseCaptureOptions(opt *CaptureOptions) string

ParseCaptureOptions parses capture options string

func ParseCommandWithoutArguments

func ParseCommandWithoutArguments(opt *CommonOptions, command string) []string

ParseCommandWithoutArguments returns a command string without arguments

func ParseCommonOptions

func ParseCommonOptions(opt *CommonOptions, command string, withUri bool) string

ParseCommonOptions returns a command options string

func ParseProbeCommand

func ParseProbeCommand(opt *ProbeOptions) string

ParseProbeCommand parses probe command string

func ParseSliceAndCaptureCommand

func ParseSliceAndCaptureCommand(opt *SliceAndCaptureOptions) string

ParseSliceAndCaptureCommand parses slice and capture command string

func ParseSliceCommand

func ParseSliceCommand(opt *SliceOptions) string

ParseSliceCommand parses slice command string

func ParseSliceOptions

func ParseSliceOptions(opt *SliceOptions) string

ParseSliceOptions parses slice options string

Types

type CaptureOptions

type CaptureOptions struct {
	CommonOptions
	Rate float32 // Frame capture rate, one frame per 1/rate second, e.g. 0.5
	Size string  // Captured image size in the form of <width>x<height>, e.g. 1024x768

	// The following options have default value
	MaxFrames int  // Maximum capture number, default to 0 (no limit)
	Debug     bool // Enable debug mode (print frame number & time point on captured images)
	Mode      int  // Capture mode, default to CaptureModeByInterval
	Frame     int  // Capture every n frame, available under CaptureModeByFrame
}

CaptureOptions options for capturing images

type Command

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

func NewCommand

func NewCommand() *Command

NewCommand creates a new FFmpeg command instance

func (*Command) Capture

func (c *Command) Capture(opt *CaptureOptions) error

Capture captures specified input media into images NOTE:

  1. The output directory MUST BE EMPTY. Command iterates files in output directory to determine the last index after FFmpeg process finishes, any other files may cause Command block (unable to exit)

func (*Command) Close

func (c *Command) Close() error

Close kills FFmpeg process, removes watcher and deletes output directory

func (*Command) Error

func (c *Command) Error() error

Error returns command error

func (*Command) IsClosed

func (c *Command) IsClosed() bool

IsClosed returns whether the command is closed

func (*Command) IsFinished

func (c *Command) IsFinished() bool

IsFinished testifies whether the command is finished

func (*Command) LastCaptureIndex

func (c *Command) LastCaptureIndex() int64

LastCaptureIndex returns last Capture output index, only available after FFmpeg process finished

func (*Command) LastIndex

func (c *Command) LastIndex() int64

LastIndex returns last output index, only available after FFmpeg process finished

func (*Command) LastSliceIndex

func (c *Command) LastSliceIndex() int64

LastSliceIndex returns last slice output index, only available after FFmpeg process finished

func (*Command) ProbeStreams

func (c *Command) ProbeStreams(opt *ProbeOptions) (st *StreamInfo, err error)

ProbeStreams probes media stream info NOTE:

  1. Will retry once on connection timeout for both file and stream
  2. Will retry several times when RetryStreamOnError is enabled for stream

func (*Command) ReadOutput

func (c *Command) ReadOutput() (o *Output, err error, ok bool, finished bool)

ReadOutput reads output from the underlying queue, also indicates whether all output are read. NOTE: Must break on finished and error in a for loop, e.g.:

for {
		o, err, ok, finished := cmd.ReadOutput()
		// 1. Check whether there is an error
		if err != nil {
			fmt.Println(err)
			break
		}
		// 2. Check whether FFmpeg is finished
		if finished {
			fmt.Println("finished")
			break
		}
		// 3. Check whether an output file is read
		if ok {
			fmt.Printf("[%v]: bytes: %v\n", o.Index, len(o.Content))
		}
}

func (*Command) Slice

func (c *Command) Slice(opt *SliceOptions) error

Slice slices specified input media into speech fragments NOTE:

  1. The output directory MUST BE EMPTY. Command iterates files in output directory to determine the last index after FFmpeg process finishes, any other files may cause Command block (unable to exit)

func (*Command) SliceAndCapture

func (c *Command) SliceAndCapture(opt *SliceAndCaptureOptions) error

SliceAndCapture slices specified input media into speech fragments and captures specified input media into images NOTE:

  1. The output directory MUST BE EMPTY. Command iterates files in output directory to determine the last index after FFmpeg process finishes, any other files may cause Command block (unable to exit)
  2. The input source must have both video and voice streams

func (*Command) Stats

func (c *Command) Stats() OutputStats

Stats returns command output statistics

type CommonOptions

type CommonOptions struct {
	Uri               string // Video, speech, stream url or file path
	OutputDir         string // Output directory
	Suffix            string // Output file suffix, e.g. jpg, png, wav
	SEIOutputDir      string // SEI fragment output directory
	SEIFragmentSuffix string // SEI fragment suffix
	MediaId           string // Media id
	IsStream          bool   // Whether the media is a stream
	IsFile            bool   // Whether the media is a local file
	DecodeSEI         bool   // Whether to decode SEI
	PreserveOutput    bool   // Whether to preserve outputs (not deleting output), not recommended for production usage
	Proxy             string // HTTP proxy
	LogLevel          string // FFmpeg log level
	DockerCommand     string // FFmpeg docker command
	IOTimeout         int    // Timeout for FFmpeg IO operations in seconds
	// contains filtered or unexported fields
}

CommonOptions common options for FFmpeg command

func (*CommonOptions) GetIOTimeout

func (opt *CommonOptions) GetIOTimeout() int

GetIOTimeout returns a valid IOTimeout value default to DefaultIOTimeout

func (*CommonOptions) GetLogLevel

func (opt *CommonOptions) GetLogLevel() string

GetLogLevel returns a valid log level

func (*CommonOptions) HttpProxy

func (opt *CommonOptions) HttpProxy() string

HttpProxy returns a valid HTTP proxy address prefixed with scheme

type Format

type Format struct {
	FormatName string `json:"format_name"`
	FileName   string `json:"filename"`
	StartTime  string `json:"start_time"`
	Duration   string `json:"duration"`
	Size       string `json:"size"`
	BitRate    string `json:"bit_rate"`
	ProbeScore int    `json:"probe_score"`
}

Format media format

func (*Format) GetDuration

func (f *Format) GetDuration() (float64, error)

GetDuration gets media duration

func (*Format) GetSize

func (f *Format) GetSize() (int64, error)

GetSize gets media file size in bytes

type Output

type Output struct {
	Type         int      // Output file type
	Index        int64    // Output file index
	Content      []byte   // Output file content
	Suffix       string   // Output file suffix
	Last         bool     // Whether output file is the last fragment/image
	LastSliced   bool     // Whether output file is the last fragment/image
	LastCaptured bool     // Whether output file is the last fragment/image
	SEIInfo      []string // SEI info

	// Captured image
	Position int64   // Capture frame position (at n-th second)
	Second   float64 // Capture frame or audio segment segment second
}

Output captured image or sliced audio segment

type OutputModifier

type OutputModifier func(*Output)

type OutputStats

type OutputStats struct {
	Start    time.Time // Time started
	End      time.Time // Time ended
	Duration int64     // Process time
	Output   int       // Number of captured images or sliced audio segments
	Bytes    int64     // Number of output file length
}

OutputStats capture/sliced statistics

type ProbeOptions

type ProbeOptions struct {
	Uri                string        // Video, speech, stream url or file path
	IsStream           bool          // Whether the media is a stream
	IsFile             bool          // Whether the media is a local file
	Proxy              string        // HTTP proxy
	RetryStreamOnError bool          // Whether to retry probing stream on error when uri is a stream
	RetryInterval      time.Duration // Interval between retries
	MaxRetry           int           // Number of maximum retries
	LogLevel           string        // FFmpeg log level
	DockerCommand      string        // FFmpeg docker command
}

ProbeOptions stream probing options

func (*ProbeOptions) GetLogLevel

func (opt *ProbeOptions) GetLogLevel() string

GetLogLevel returns a valid log level

func (*ProbeOptions) HttpProxy

func (opt *ProbeOptions) HttpProxy() string

HttpProxy returns a valid HTTP proxy address prefixed with scheme

type SliceAndCaptureOptions

type SliceAndCaptureOptions struct {
	CommonOptions
	*SliceOptions
	*CaptureOptions
	HasSpeechStream bool
	HasImageStream  bool
}

type SliceOptions

type SliceOptions struct {
	CommonOptions

	// The following options must be set, use NewDefaultSliceOptions to get a pre-defined option
	DisableVideo      bool   // Disable video stream while slicing
	Coding            string // Audio encoding
	SamplingFrequency int    // Audio sampling frequency
	Channels          int    // Audio channels
	Format            string // Audio format
	FragmentDuration  int    // Sliced fragment duration in seconds
}

SliceOptions options for slicing audio segments

func NewDefaultSliceOptions

func NewDefaultSliceOptions() *SliceOptions

type Stream

type Stream struct {
	Index              int    `json:"index"`
	CodecName          string `json:"codec_name"`
	CodecType          string `json:"codec_type"`
	Width              int    `json:"width"`
	Height             int    `json:"height"`
	DisplayAspectRatio string `json:"display_aspect_ratio"`
	StartTime          string `json:"start_time"`
	Duration           string `json:"duration"`
	AvgFrameRate       string `json:"avg_frame_rate"`
	Frames             string `json:"nb_frames"`
	SampleRate         string `json:"sample_rate"`
}

Stream the stream info

func (*Stream) GetDuration

func (s *Stream) GetDuration() (float64, error)

GetDuration gets stream's duration

func (*Stream) GetFrameRate

func (s *Stream) GetFrameRate() (float64, error)

GetFrameRate gets stream's frame rate

func (*Stream) GetFrames

func (s *Stream) GetFrames() (int64, error)

GetFrames gets stream's number of frames

func (*Stream) GetStartTime

func (s *Stream) GetStartTime() (float64, error)

GetStartTime gets stream's start time

type StreamInfo

type StreamInfo struct {
	Streams []Stream `json:"streams"` // Media streams, in the most common cases #0 is video, #1 is audio
	Format  Format   `json:"format"`  // Media format
}

StreamInfo media stream info

func (*StreamInfo) GetAudioDuration

func (st *StreamInfo) GetAudioDuration() (float64, error)

GetAudioDuration tries to acquire media duration from stream, otherwise from format

func (*StreamInfo) GetVideoDuration

func (st *StreamInfo) GetVideoDuration() (float64, error)

GetVideoDuration tries to acquire media duration from stream, otherwise from format

func (*StreamInfo) HasAudioStream

func (st *StreamInfo) HasAudioStream() (int, bool)

HasAudioStream returns whether the media has audio stream and its stream index

func (*StreamInfo) HasVideoStream

func (st *StreamInfo) HasVideoStream() (int, bool)

HasVideoStream returns whether the media has video stream and its stream index

Jump to

Keyboard shortcuts

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