ffmpeg

package
v0.19.1 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2023 License: AGPL-3.0 Imports: 23 Imported by: 1

Documentation

Overview

Package ffmpeg provides a wrapper around the ffmpeg and ffprobe executables.

Index

Constants

View Source
const (
	Mp4      Container = "mp4"
	M4v      Container = "m4v"
	Mov      Container = "mov"
	Wmv      Container = "wmv"
	Webm     Container = "webm"
	Matroska Container = "matroska"
	Avi      Container = "avi"
	Flv      Container = "flv"
	Mpegts   Container = "mpegts"

	Aac                ProbeAudioCodec = "aac"
	Mp3                ProbeAudioCodec = "mp3"
	Opus               ProbeAudioCodec = "opus"
	Vorbis             ProbeAudioCodec = "vorbis"
	MissingUnsupported ProbeAudioCodec = ""

	Mp4Ffmpeg      string = "mov,mp4,m4a,3gp,3g2,mj2" // browsers support all of them
	M4vFfmpeg      string = "mov,mp4,m4a,3gp,3g2,mj2" // so we don't care that ffmpeg
	MovFfmpeg      string = "mov,mp4,m4a,3gp,3g2,mj2" // can't differentiate between them
	WmvFfmpeg      string = "asf"
	WebmFfmpeg     string = "matroska,webm"
	MatroskaFfmpeg string = "matroska,webm"
	AviFfmpeg      string = "avi"
	FlvFfmpeg      string = "flv"
	MpegtsFfmpeg   string = "mpegts"
	H264           string = "h264"
	H265           string = "h265" // found in rare cases from a faulty encoder
	Hevc           string = "hevc"
	Vp8            string = "vp8"
	Vp9            string = "vp9"
	Mkv            string = "mkv" // only used from the browser to indicate mkv support
	Hls            string = "hls" // only used from the browser to indicate hls support
)
View Source
const (
	MimeWebm   string = "video/webm"
	MimeMkv    string = "video/x-matroska"
	MimeMp4    string = "video/mp4"
	MimeHLS    string = "application/vnd.apple.mpegurl"
	MimeMpegts string = "video/MP2T"
)

Variables

View Source
var (
	// ErrUnsupportedVideoCodecForBrowser is returned when the video codec is not supported for browser streaming.
	ErrUnsupportedVideoCodecForBrowser = errors.New("unsupported video codec for browser")

	// ErrUnsupportedVideoCodecContainer is returned when the video codec/container combination is not supported for browser streaming.
	ErrUnsupportedVideoCodecContainer = errors.New("video codec/container combination is unsupported for browser streaming")

	// ErrUnsupportedAudioCodecContainer is returned when the audio codec/container combination is not supported for browser streaming.
	ErrUnsupportedAudioCodecContainer = errors.New("audio codec/container combination is unsupported for browser streaming")
)
View Source
var (
	StreamFormatHLS = StreamFormat{

		MimeType: MimeMpegts,
		// contains filtered or unexported fields
	}

	StreamFormatH264 = StreamFormat{

		MimeType: MimeMp4,
		// contains filtered or unexported fields
	}

	StreamFormatVP9 = StreamFormat{

		MimeType: MimeWebm,
		// contains filtered or unexported fields
	}

	StreamFormatVP8 = StreamFormat{

		MimeType: MimeWebm,
		// contains filtered or unexported fields
	}

	StreamFormatHEVC = StreamFormat{

		MimeType: MimeMp4,
		// contains filtered or unexported fields
	}

	// it is very common in MKVs to have just the audio codec unsupported
	// copy the video stream, transcode the audio and serve as Matroska
	StreamFormatMKVAudio = StreamFormat{

		MimeType: MimeMkv,
		// contains filtered or unexported fields
	}
)

Functions

func Download

func Download(ctx context.Context, configDirectory string) error

func GetPaths

func GetPaths(paths []string) (string, string)

func IsStreamable added in v0.3.0

func IsStreamable(videoCodec string, audioCodec ProbeAudioCodec, container Container) error

IsStreamable returns nil if the file is streamable, or an error if it is not.

func IsValidAudioForContainer added in v0.2.0

func IsValidAudioForContainer(audio ProbeAudioCodec, format Container) bool

IsValidAudioForContainer returns true if the audio codec is valid for the container.

func WriteHLSPlaylist added in v0.3.0

func WriteHLSPlaylist(duration float64, baseUrl string, w io.Writer)

WriteHLSPlaylist writes a HLS playlist to w using baseUrl as the base URL for TS streams.

Types

type Arger added in v0.15.0

type Arger interface {
	Args() []string
}

Arger is an interface that can be used to append arguments to an Args slice.

type Args added in v0.15.0

type Args []string

Args represents a slice of arguments to be passed to ffmpeg.

func (Args) AppendArgs added in v0.15.0

func (a Args) AppendArgs(o Arger) Args

AppendArgs appends the given Arger to the Args and returns the result.

func (Args) Args added in v0.15.0

func (a Args) Args() []string

Args returns a string slice of the arguments.

func (Args) AudioBitrate added in v0.15.0

func (a Args) AudioBitrate(b string) Args

AudioBitrate adds the -b:a argument with b and returns the result.

func (Args) AudioCodec added in v0.15.0

func (a Args) AudioCodec(c AudioCodec) Args

AudioCodec adds the given audio codec and returns the result.

func (Args) Duration added in v0.15.0

func (a Args) Duration(seconds float64) Args

Duration sets the duration (-t) to the given seconds and returns the result.

func (Args) FixedQualityScaleVideo added in v0.15.0

func (a Args) FixedQualityScaleVideo(q int) Args

FixedQualityScaleVideo adds the -q:v argument with q and returns the result.

func (Args) Format added in v0.15.0

func (a Args) Format(f Format) Args

Format adds the format flag with f and returns the result.

func (Args) ImageFormat added in v0.15.0

func (a Args) ImageFormat(f ImageFormat) Args

ImageFormat adds the image format (using -f) and returns the result.

func (Args) Input added in v0.15.0

func (a Args) Input(i string) Args

Input adds the input (-i) and returns the result.

func (Args) LogLevel added in v0.15.0

func (a Args) LogLevel(l LogLevel) Args

LogLevel sets the LogLevel to l and returns the result.

func (Args) MaxMuxingQueueSize added in v0.15.0

func (a Args) MaxMuxingQueueSize(s int) Args

MaxMuxingQueueSize adds the -max_muxing_queue_size argument with s and returns the result.

func (Args) NullOutput added in v0.15.0

func (a Args) NullOutput() Args

NullOutput adds a null output and returns the result. On Windows, this outputs to NUL, on everything else, /dev/null.

func (Args) Output added in v0.15.0

func (a Args) Output(o string) Args

Output adds the output o and returns the result.

func (Args) Overwrite added in v0.15.0

func (a Args) Overwrite() Args

Overwrite adds the overwrite flag (-y) and returns the result.

func (Args) Seek added in v0.15.0

func (a Args) Seek(seconds float64) Args

Seek adds a seek (-ss) to the given seconds and returns the result.

func (Args) SkipAudio added in v0.15.0

func (a Args) SkipAudio() Args

SkipAudio adds the skip audio flag (-an) and returns the result.

func (Args) VSync added in v0.15.0

func (a Args) VSync(m VSyncMethod) Args

VSync adds the VsyncMethod and returns the result.

func (Args) VideoCodec added in v0.15.0

func (a Args) VideoCodec(c VideoCodec) Args

VideoCodec adds the given video codec and returns the result.

func (Args) VideoFilter added in v0.15.0

func (a Args) VideoFilter(vf VideoFilter) Args

VideoFilter adds the vf video filter and returns the result.

func (Args) VideoFrames added in v0.15.0

func (a Args) VideoFrames(f int) Args

VideoFrames adds the -frames:v with f and returns the result.

func (Args) XError added in v0.15.0

func (a Args) XError() Args

XError adds the -xerror flag and returns the result.

type AudioCodec added in v0.2.0

type AudioCodec string
var (
	AudioCodecAAC     AudioCodec = "aac"
	AudioCodecLibOpus AudioCodec = "libopus"
	AudioCodecCopy    AudioCodec = "copy"
)

func (AudioCodec) Args added in v0.15.0

func (c AudioCodec) Args() []string

type Container added in v0.2.0

type Container string

func MatchContainer added in v0.2.0

func MatchContainer(format string, filePath string) (Container, error)

type FFMpeg added in v0.15.0

type FFMpeg string

FFMpeg provides an interface to ffmpeg.

func (FFMpeg) CalculateFrameRate added in v0.15.0

func (f FFMpeg) CalculateFrameRate(ctx context.Context, v *VideoFile) (*FrameInfo, error)

CalculateFrameRate calculates the frame rate and number of frames of the video file. Used where the frame rate or NbFrames is missing or invalid in the ffprobe output.

func (*FFMpeg) Command added in v0.15.0

func (f *FFMpeg) Command(ctx context.Context, args []string) *exec.Cmd

Returns an exec.Cmd that can be used to run ffmpeg using args.

func (FFMpeg) Generate added in v0.15.0

func (f FFMpeg) Generate(ctx context.Context, args Args) error

Generate runs ffmpeg with the given args and waits for it to finish. Returns an error if the command fails. If the command fails, the return value will be of type *exec.ExitError.

func (FFMpeg) GenerateOutput added in v0.15.0

func (f FFMpeg) GenerateOutput(ctx context.Context, args []string, stdin io.Reader) ([]byte, error)

GenerateOutput runs ffmpeg with the given args and returns it standard output.

func (*FFMpeg) GetTranscodeStream added in v0.15.0

func (f *FFMpeg) GetTranscodeStream(ctx context.Context, options TranscodeStreamOptions) (*Stream, error)

GetTranscodeStream starts the live transcoding process using ffmpeg and returns a stream.

type FFProbe added in v0.11.0

type FFProbe string

FFProbe provides an interface to the ffprobe executable.

func (*FFProbe) GetReadFrameCount added in v0.13.0

func (f *FFProbe) GetReadFrameCount(path string) (int64, error)

GetReadFrameCount counts the actual frames of the video file. Used when the frame count is missing or incorrect.

func (*FFProbe) NewVideoFile added in v0.11.0

func (f *FFProbe) NewVideoFile(videoPath string) (*VideoFile, error)

NewVideoFile runs ffprobe on the given path and returns a VideoFile.

type FFProbeJSON

type FFProbeJSON struct {
	Format struct {
		BitRate        string `json:"bit_rate"`
		Duration       string `json:"duration"`
		Filename       string `json:"filename"`
		FormatLongName string `json:"format_long_name"`
		FormatName     string `json:"format_name"`
		NbPrograms     int    `json:"nb_programs"`
		NbStreams      int    `json:"nb_streams"`
		ProbeScore     int    `json:"probe_score"`
		Size           string `json:"size"`
		StartTime      string `json:"start_time"`
		Tags           struct {
			CompatibleBrands string        `json:"compatible_brands"`
			CreationTime     json.JSONTime `json:"creation_time"`
			Encoder          string        `json:"encoder"`
			MajorBrand       string        `json:"major_brand"`
			MinorVersion     string        `json:"minor_version"`
			Title            string        `json:"title"`
			Comment          string        `json:"comment"`
		} `json:"tags"`
	} `json:"format"`
	Streams []FFProbeStream `json:"streams"`
	Error   struct {
		Code   int    `json:"code"`
		String string `json:"string"`
	} `json:"error"`
}

FFProbeJSON is the JSON output of ffprobe.

type FFProbeStream

type FFProbeStream struct {
	AvgFrameRate       string `json:"avg_frame_rate"`
	BitRate            string `json:"bit_rate"`
	BitsPerRawSample   string `json:"bits_per_raw_sample,omitempty"`
	ChromaLocation     string `json:"chroma_location,omitempty"`
	CodecLongName      string `json:"codec_long_name"`
	CodecName          string `json:"codec_name"`
	CodecTag           string `json:"codec_tag"`
	CodecTagString     string `json:"codec_tag_string"`
	CodecTimeBase      string `json:"codec_time_base"`
	CodecType          string `json:"codec_type"`
	CodedHeight        int    `json:"coded_height,omitempty"`
	CodedWidth         int    `json:"coded_width,omitempty"`
	DisplayAspectRatio string `json:"display_aspect_ratio,omitempty"`
	Disposition        struct {
		AttachedPic     int `json:"attached_pic"`
		CleanEffects    int `json:"clean_effects"`
		Comment         int `json:"comment"`
		Default         int `json:"default"`
		Dub             int `json:"dub"`
		Forced          int `json:"forced"`
		HearingImpaired int `json:"hearing_impaired"`
		Karaoke         int `json:"karaoke"`
		Lyrics          int `json:"lyrics"`
		Original        int `json:"original"`
		TimedThumbnails int `json:"timed_thumbnails"`
		VisualImpaired  int `json:"visual_impaired"`
	} `json:"disposition"`
	Duration          string `json:"duration"`
	DurationTs        int    `json:"duration_ts"`
	HasBFrames        int    `json:"has_b_frames,omitempty"`
	Height            int    `json:"height,omitempty"`
	Index             int    `json:"index"`
	IsAvc             string `json:"is_avc,omitempty"`
	Level             int    `json:"level,omitempty"`
	NalLengthSize     string `json:"nal_length_size,omitempty"`
	NbFrames          string `json:"nb_frames"`
	NbReadFrames      string `json:"nb_read_frames"`
	PixFmt            string `json:"pix_fmt,omitempty"`
	Profile           string `json:"profile"`
	RFrameRate        string `json:"r_frame_rate"`
	Refs              int    `json:"refs,omitempty"`
	SampleAspectRatio string `json:"sample_aspect_ratio,omitempty"`
	StartPts          int    `json:"start_pts"`
	StartTime         string `json:"start_time"`
	Tags              struct {
		CreationTime json.JSONTime `json:"creation_time"`
		HandlerName  string        `json:"handler_name"`
		Language     string        `json:"language"`
		Rotate       string        `json:"rotate"`
	} `json:"tags"`
	TimeBase      string `json:"time_base"`
	Width         int    `json:"width,omitempty"`
	BitsPerSample int    `json:"bits_per_sample,omitempty"`
	ChannelLayout string `json:"channel_layout,omitempty"`
	Channels      int    `json:"channels,omitempty"`
	MaxBitRate    string `json:"max_bit_rate,omitempty"`
	SampleFmt     string `json:"sample_fmt,omitempty"`
	SampleRate    string `json:"sample_rate,omitempty"`
}

FFProbeStream is a JSON representation of an ffmpeg stream.

type Format added in v0.15.0

type Format string

Format represents the input/output format for ffmpeg.

var (
	FormatConcat   Format = "concat"
	FormatImage2   Format = "image2"
	FormatRawVideo Format = "rawvideo"
	FormatMpegTS   Format = "mpegts"
	FormatMP4      Format = "mp4"
	FormatWebm     Format = "webm"
	FormatMatroska Format = "matroska"
)

func (Format) Args added in v0.15.0

func (f Format) Args() []string

Args converts the Format to a slice of arguments to be passed to ffmpeg.

type FrameInfo added in v0.15.0

type FrameInfo struct {
	FrameRate      float64
	NumberOfFrames int
}

FrameInfo contains the number of frames and the frame rate for a video file.

type ImageFormat added in v0.15.0

type ImageFormat string

ImageFormat represents the input format for an image for ffmpeg.

var (
	ImageFormatJpeg ImageFormat = "mjpeg"
	ImageFormatPng  ImageFormat = "png_pipe"
	ImageFormatWebp ImageFormat = "webp_pipe"

	ImageFormatImage2Pipe ImageFormat = "image2pipe"
)

func (ImageFormat) Args added in v0.15.0

func (f ImageFormat) Args() []string

Args converts the ImageFormat to a slice of arguments to be passed to ffmpeg.

type LogLevel added in v0.15.0

type LogLevel string

LogLevel represents the log level of ffmpeg.

var (
	LogLevelQuiet   LogLevel = "quiet"
	LogLevelPanic   LogLevel = "panic"
	LogLevelFatal   LogLevel = "fatal"
	LogLevelError   LogLevel = "error"
	LogLevelWarning LogLevel = "warning"
	LogLevelInfo    LogLevel = "info"
	LogLevelVerbose LogLevel = "verbose"
	LogLevelDebug   LogLevel = "debug"
	LogLevelTrace   LogLevel = "trace"
)

LogLevels for ffmpeg. See -v entry under https://ffmpeg.org/ffmpeg.html#Generic-options

func (LogLevel) Args added in v0.15.0

func (l LogLevel) Args() []string

Args returns the arguments to set the log level in ffmpeg.

type ProbeAudioCodec added in v0.15.0

type ProbeAudioCodec string

type Stream added in v0.3.0

type Stream struct {
	Stdout io.ReadCloser
	Cmd    *exec.Cmd
	// contains filtered or unexported fields
}

Stream represents an ongoing transcoded stream.

func (*Stream) Serve added in v0.3.0

func (s *Stream) Serve(w http.ResponseWriter, r *http.Request)

Serve is an http handler function that serves the stream.

type StreamFormat added in v0.15.0

type StreamFormat struct {
	MimeType string
	// contains filtered or unexported fields
}

StreamFormat represents a transcode stream format.

type TranscodeStreamOptions added in v0.3.0

type TranscodeStreamOptions struct {
	Input            string
	Codec            StreamFormat
	StartTime        float64
	MaxTranscodeSize int

	// original video dimensions
	VideoWidth  int
	VideoHeight int

	// transcode the video, remove the audio
	// in some videos where the audio codec is not supported by ffmpeg
	// ffmpeg fails if you try to transcode the audio
	VideoOnly bool

	// arguments added before the input argument
	ExtraInputArgs []string
	// arguments added before the output argument
	ExtraOutputArgs []string
}

TranscodeStreamOptions represents options for live transcoding a video file.

type VSyncMethod added in v0.15.0

type VSyncMethod string

VSyncMethod represents the vsync method of ffmpeg.

var (
	VSyncMethodPassthrough VSyncMethod = "0"
	VSyncMethodCFR         VSyncMethod = "1"
	VSyncMethodVFR         VSyncMethod = "2"
	VSyncMethodDrop        VSyncMethod = "drop"
	VSyncMethodAuto        VSyncMethod = "-1"
)

Video sync methods for ffmpeg. See -vsync entry under https://ffmpeg.org/ffmpeg.html#Advanced-options

func (VSyncMethod) Args added in v0.15.0

func (m VSyncMethod) Args() []string

Args returns the arguments to set the vsync method in ffmpeg.

type VideoCodec added in v0.15.0

type VideoCodec string
var (
	VideoCodecLibX264 VideoCodec = "libx264"
	VideoCodecLibWebP VideoCodec = "libwebp"
	VideoCodecBMP     VideoCodec = "bmp"
	VideoCodecMJpeg   VideoCodec = "mjpeg"
	VideoCodecVP9     VideoCodec = "libvpx-vp9"
	VideoCodecVPX     VideoCodec = "libvpx"
	VideoCodecLibX265 VideoCodec = "libx265"
	VideoCodecCopy    VideoCodec = "copy"
)

func (VideoCodec) Args added in v0.15.0

func (c VideoCodec) Args() []string

type VideoFile

type VideoFile struct {
	JSON        FFProbeJSON
	AudioStream *FFProbeStream
	VideoStream *FFProbeStream

	Path      string
	Title     string
	Comment   string
	Container string
	// FileDuration is the declared (meta-data) duration of the *file*.
	// In most cases (sprites, previews, etc.) we actually care about the duration of the video stream specifically,
	// because those two can differ slightly (e.g. audio stream longer than the video stream, making the whole file
	// longer).
	FileDuration        float64
	VideoStreamDuration float64
	StartTime           float64
	Bitrate             int64
	Size                int64
	CreationTime        time.Time

	VideoCodec   string
	VideoBitrate int64
	Width        int
	Height       int
	FrameRate    float64
	Rotation     int64
	FrameCount   int64

	AudioCodec string
}

VideoFile represents the ffprobe output for a video file.

func (*VideoFile) TranscodeScale added in v0.15.0

func (v *VideoFile) TranscodeScale(maxSize int) (int, int)

TranscodeScale calculates the dimension scaling for a transcode, where maxSize is the maximum size of the longest dimension of the input video. If no scaling is required, then returns 0, 0. Returns -2 for the dimension that will scale to maintain aspect ratio.

type VideoFilter added in v0.15.0

type VideoFilter string

VideoFilter represents video filter parameters to be passed to ffmpeg.

func (VideoFilter) Append added in v0.15.0

func (f VideoFilter) Append(s string) VideoFilter

Append returns a VideoFilter appending the given string.

func (VideoFilter) Args added in v0.15.0

func (f VideoFilter) Args() []string

Args converts the video filter parameters to a slice of arguments to be passed to ffmpeg. Returns an empty slice if the filter is empty.

func (VideoFilter) Fps added in v0.15.0

func (f VideoFilter) Fps(fps int) VideoFilter

Fps returns a VideoFilter setting the frames per second.

func (VideoFilter) ScaleDimensions added in v0.15.0

func (f VideoFilter) ScaleDimensions(w, h int) VideoFilter

ScaleDimesions returns a VideoFilter scaling using w and h. Use -n to maintain aspect ratio and maintain as multiple of n.

func (VideoFilter) ScaleHeight added in v0.15.0

func (f VideoFilter) ScaleHeight(h int) VideoFilter

func (VideoFilter) ScaleMax added in v0.15.0

func (f VideoFilter) ScaleMax(inputWidth, inputHeight, maxSize int) VideoFilter

ScaleMax returns a VideoFilter scaling to maxSize. It will scale width if it is larger than height, otherwise it will scale height.

func (VideoFilter) ScaleMaxSize added in v0.15.0

func (f VideoFilter) ScaleMaxSize(maxDimensions int) VideoFilter

ScaleMaxSize returns a VideoFilter scaling to maxDimensions, maintaining aspect ratio using force_original_aspect_ratio=decrease.

func (VideoFilter) ScaleWidth added in v0.15.0

func (f VideoFilter) ScaleWidth(w int) VideoFilter

ScaleWidth returns a VideoFilter scaling the width to the given width, maintaining aspect ratio and a height as a multiple of 2.

func (VideoFilter) Select added in v0.15.0

func (f VideoFilter) Select(frame int) VideoFilter

Select returns a VideoFilter to select the given frame.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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