ffmpeg

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2024 License: AGPL-3.0 Imports: 27 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 (
	MimeWebmVideo string = "video/webm"
	MimeWebmAudio string = "audio/webm"
	MimeMkvVideo  string = "video/x-matroska"
	MimeMkvAudio  string = "audio/x-matroska"
	MimeMp4Video  string = "video/mp4"
	MimeMp4Audio  string = "audio/mp4"
)
View Source
const (
	MimeHLS    string = "application/vnd.apple.mpegurl"
	MimeMpegTS string = "video/MP2T"
	MimeDASH   string = "application/dash+xml"
)

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 (
	// Software codec's
	VideoCodecLibX264 = makeVideoCodec("x264", "libx264")
	VideoCodecLibWebP = makeVideoCodec("WebP", "libwebp")
	VideoCodecBMP     = makeVideoCodec("BMP", "bmp")
	VideoCodecMJpeg   = makeVideoCodec("Jpeg", "mjpeg")
	VideoCodecVP9     = makeVideoCodec("VPX-VP9", "libvpx-vp9")
	VideoCodecVPX     = makeVideoCodec("VPX-VP8", "libvpx")
	VideoCodecLibX265 = makeVideoCodec("x265", "libx265")
	VideoCodecCopy    = makeVideoCodec("Copy", "copy")
)
View Source
var (
	// Hardware codec's
	VideoCodecN264  = makeVideoCodec("H264 NVENC", "h264_nvenc")
	VideoCodecN264H = makeVideoCodec("H264 NVENC HQ profile", "h264_nvenc")
	VideoCodecI264  = makeVideoCodec("H264 Intel Quick Sync Video (QSV)", "h264_qsv")
	VideoCodecI264C = makeVideoCodec("H264 Intel Quick Sync Video (QSV) Compatibility profile", "h264_qsv")
	VideoCodecA264  = makeVideoCodec("H264 Advanced Media Framework (AMF)", "h264_amf")
	VideoCodecM264  = makeVideoCodec("H264 VideoToolbox", "h264_videotoolbox")
	VideoCodecV264  = makeVideoCodec("H264 VAAPI", "h264_vaapi")
	VideoCodecR264  = makeVideoCodec("H264 V4L2M2M", "h264_v4l2m2m")
	VideoCodecO264  = makeVideoCodec("H264 OMX", "h264_omx")
	VideoCodecIVP9  = makeVideoCodec("VP9 Intel Quick Sync Video (QSV)", "vp9_qsv")
	VideoCodecVVP9  = makeVideoCodec("VP9 VAAPI", "vp9_vaapi")
	VideoCodecVVPX  = makeVideoCodec("VP8 VAAPI", "vp8_vaapi")
)
View Source
var (
	StreamTypeHLS = &StreamType{
		Name:          "hls",
		SegmentType:   SegmentTypeTS,
		ServeManifest: serveHLSManifest,
		Args: func(codec VideoCodec, segment int, videoFilter VideoFilter, videoOnly bool, outputDir string) (args Args) {
			args = CodecInit(codec)
			args = append(args,
				"-flags", "+cgop",
				"-force_key_frames", fmt.Sprintf("expr:gte(t,n_forced*%d)", segmentLength),
			)
			args = args.VideoFilter(videoFilter)
			if videoOnly {
				args = append(args, "-an")
			} else {
				args = append(args,
					"-c:a", "aac",
					"-ac", "2",
				)
			}
			args = append(args,
				"-sn",
				"-copyts",
				"-avoid_negative_ts", "disabled",
				"-f", "hls",
				"-start_number", fmt.Sprint(segment),
				"-hls_time", fmt.Sprint(segmentLength),
				"-hls_flags", "split_by_time",
				"-hls_segment_type", "mpegts",
				"-hls_playlist_type", "vod",
				"-hls_segment_filename", filepath.Join(outputDir, ".%d.ts"),
				filepath.Join(outputDir, "manifest.m3u8"),
			)
			return
		},
	}
	StreamTypeHLSCopy = &StreamType{
		Name:          "hls-copy",
		SegmentType:   SegmentTypeTS,
		ServeManifest: serveHLSManifest,
		Args: func(codec VideoCodec, segment int, videoFilter VideoFilter, videoOnly bool, outputDir string) (args Args) {
			args = CodecInit(codec)
			if videoOnly {
				args = append(args, "-an")
			} else {
				args = append(args,
					"-c:a", "aac",
					"-ac", "2",
				)
			}
			args = append(args,
				"-sn",
				"-copyts",
				"-avoid_negative_ts", "disabled",
				"-f", "hls",
				"-start_number", fmt.Sprint(segment),
				"-hls_time", fmt.Sprint(segmentLength),
				"-hls_flags", "split_by_time",
				"-hls_segment_type", "mpegts",
				"-hls_playlist_type", "vod",
				"-hls_segment_filename", filepath.Join(outputDir, ".%d.ts"),
				filepath.Join(outputDir, "manifest.m3u8"),
			)
			return
		},
	}
	StreamTypeDASHVideo = &StreamType{
		Name:          "dash-v",
		SegmentType:   SegmentTypeWEBMVideo,
		ServeManifest: serveDASHManifest,
		Args: func(codec VideoCodec, segment int, videoFilter VideoFilter, videoOnly bool, outputDir string) (args Args) {

			init := ".init"
			if segment == 0 {
				init = "init"
			}

			args = CodecInit(codec)
			args = append(args,
				"-force_key_frames", fmt.Sprintf("expr:gte(t,n_forced*%d)", segmentLength),
			)

			args = args.VideoFilter(videoFilter)
			args = append(args,
				"-copyts",
				"-avoid_negative_ts", "disabled",
				"-map", "0:v:0",
				"-f", "webm_chunk",
				"-chunk_start_index", fmt.Sprint(segment),
				"-header", filepath.Join(outputDir, init+"_v.webm"),
				filepath.Join(outputDir, ".%d_v.webm"),
			)
			return
		},
	}
	StreamTypeDASHAudio = &StreamType{
		Name:          "dash-a",
		SegmentType:   SegmentTypeWEBMAudio,
		ServeManifest: serveDASHManifest,
		Args: func(codec VideoCodec, segment int, videoFilter VideoFilter, videoOnly bool, outputDir string) (args Args) {

			init := ".init"
			if segment == 0 {
				init = "init"
			}
			args = append(args,
				"-c:a", "libopus",
				"-b:a", "96000",
				"-ar", "48000",
				"-copyts",
				"-avoid_negative_ts", "disabled",
				"-map", "0:a:0",
				"-f", "webm_chunk",
				"-chunk_start_index", fmt.Sprint(segment),
				"-audio_chunk_duration", fmt.Sprint(segmentLength*1000),
				"-header", filepath.Join(outputDir, init+"_a.webm"),
				filepath.Join(outputDir, ".%d_a.webm"),
			)
			return
		},
	}
)
View Source
var (
	SegmentTypeTS = &SegmentType{
		Format:   "%d.ts",
		MimeType: MimeMpegTS,
		MakeFilename: func(segment int) string {
			return fmt.Sprintf("%d.ts", segment)
		},
		ParseSegment: func(str string) (int, error) {
			segment, err := strconv.Atoi(str)
			if err != nil || segment < 0 {
				err = ErrInvalidSegment
			}
			return segment, err
		},
	}
	SegmentTypeWEBMVideo = &SegmentType{
		Format:   "%d_v.webm",
		MimeType: MimeWebmVideo,
		MakeFilename: func(segment int) string {
			if segment == -1 {
				return "init_v.webm"
			} else {
				return fmt.Sprintf("%d_v.webm", segment)
			}
		},
		ParseSegment: func(str string) (int, error) {
			if str == "init" {
				return -1, nil
			} else {
				segment, err := strconv.Atoi(str)
				if err != nil || segment < 0 {
					err = ErrInvalidSegment
				}
				return segment, err
			}
		},
	}
	SegmentTypeWEBMAudio = &SegmentType{
		Format:   "%d_a.webm",
		MimeType: MimeWebmAudio,
		MakeFilename: func(segment int) string {
			if segment == -1 {
				return "init_a.webm"
			} else {
				return fmt.Sprintf("%d_a.webm", segment)
			}
		},
		ParseSegment: func(str string) (int, error) {
			if str == "init" {
				return -1, nil
			} else {
				segment, err := strconv.Atoi(str)
				if err != nil || segment < 0 {
					err = ErrInvalidSegment
				}
				return segment, err
			}
		},
	}
)
View Source
var (
	StreamTypeMP4 = StreamFormat{
		MimeType: MimeMp4Video,
		Args: func(codec VideoCodec, videoFilter VideoFilter, videoOnly bool) (args Args) {
			args = CodecInit(codec)
			args = append(args, "-movflags", "frag_keyframe+empty_moov")
			args = args.VideoFilter(videoFilter)
			if videoOnly {
				args = args.SkipAudio()
			} else {
				args = append(args, "-ac", "2")
			}
			args = args.Format(FormatMP4)
			return
		},
	}
	StreamTypeWEBM = StreamFormat{
		MimeType: MimeWebmVideo,
		Args: func(codec VideoCodec, videoFilter VideoFilter, videoOnly bool) (args Args) {
			args = CodecInit(codec)
			args = args.VideoFilter(videoFilter)
			if videoOnly {
				args = args.SkipAudio()
			} else {
				args = append(args, "-ac", "2")
			}
			args = args.Format(FormatWebm)
			return
		},
	}
	StreamTypeMKV = StreamFormat{
		MimeType: MimeMkvVideo,
		Args: func(codec VideoCodec, videoFilter VideoFilter, videoOnly bool) (args Args) {
			args = CodecInit(codec)
			if videoOnly {
				args = args.SkipAudio()
			} else {
				args = args.AudioCodec(AudioCodecLibOpus)
				args = append(args,
					"-b:a", "96k",
					"-vbr", "on",
					"-ac", "2",
				)
			}
			args = args.Format(FormatMatroska)
			return
		},
	}
)
View Source
var ErrInvalidSegment = errors.New("invalid segment")

Functions

func FindFFMpeg added in v0.26.0

func FindFFMpeg(path string) string

func FindFFProbe added in v0.26.0

func FindFFProbe(path string) string

func GetFFmpegURL added in v0.26.0

func GetFFmpegURL() []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 LookPathFFMpeg added in v0.26.0

func LookPathFFMpeg() string

func LookPathFFProbe added in v0.26.0

func LookPathFFProbe() string

func ResolveFFMpeg added in v0.26.0

func ResolveFFMpeg(path string, fallbackPath string) string

ResolveFFMpeg attempts to resolve the path to the ffmpeg executable. It first looks in the provided path, then resolves from the environment, and finally looks in the fallback path. It will prefer an ffmpeg binary that has the required codec support. Returns an empty string if a valid ffmpeg cannot be found.

func ResolveFFProbe added in v0.26.0

func ResolveFFProbe(path string, fallbackPath string) string

ResolveFFMpeg attempts to resolve the path to the ffmpeg executable. It first looks in the provided path, then resolves from the environment, and finally looks in the fallback path. Returns an empty string if a valid ffmpeg cannot be found.

func ValidateFFMpeg added in v0.26.0

func ValidateFFMpeg(ffmpegPath string) error

func ValidateFFMpegCodecSupport added in v0.26.0

func ValidateFFMpegCodecSupport(ffmpegPath string) error

func ValidateFFProbe added in v0.26.0

func ValidateFFProbe(ffprobePath string) error

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 CodecInit added in v0.20.0

func CodecInit(codec VideoCodec) (args Args)

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 struct {
	// contains filtered or unexported fields
}

FFMpeg provides an interface to ffmpeg.

func NewEncoder

func NewEncoder(ffmpegPath string) *FFMpeg

Creates a new FFMpeg encoder

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) InitHWSupport added in v0.20.0

func (f *FFMpeg) InitHWSupport(ctx context.Context)

Tests all (given) hardware codec's

func (*FFMpeg) Path added in v0.26.0

func (f *FFMpeg) Path() string

type FFProbe added in v0.11.0

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

FFProbe provides an interface to the ffprobe executable.

func NewFFProbe added in v0.27.0

func NewFFProbe(path string) *FFProbe

Creates a new FFProbe instance.

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.

func (*FFProbe) Path added in v0.26.0

func (f *FFProbe) Path() string

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        int64  `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          int64  `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"`
	SideDataList  []struct {
		Rotation int `json:"rotation"`
	} `json:"side_data_list"`
}

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 SegmentType added in v0.20.0

type SegmentType struct {
	Format       string
	MimeType     string
	MakeFilename func(segment int) string
	ParseSegment func(str string) (int, error)
}

type StreamFormat added in v0.15.0

type StreamFormat struct {
	MimeType string
	Args     func(codec VideoCodec, videoFilter VideoFilter, videoOnly bool) Args
}

type StreamManager added in v0.20.0

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

func NewStreamManager added in v0.20.0

func NewStreamManager(cacheDir string, encoder *FFMpeg, ffprobe *FFProbe, config StreamManagerConfig, lockManager *fsutil.ReadLockManager) *StreamManager

func (*StreamManager) ServeManifest added in v0.20.0

func (sm *StreamManager) ServeManifest(w http.ResponseWriter, r *http.Request, streamType *StreamType, vf *models.VideoFile, resolution string)

func (*StreamManager) ServeSegment added in v0.20.0

func (sm *StreamManager) ServeSegment(w http.ResponseWriter, r *http.Request, options StreamOptions)

func (*StreamManager) ServeTranscode added in v0.20.0

func (sm *StreamManager) ServeTranscode(w http.ResponseWriter, r *http.Request, options TranscodeOptions)

func (*StreamManager) Shutdown added in v0.20.0

func (sm *StreamManager) Shutdown()

Shutdown shuts down the stream manager, killing any running transcoding processes and removing all cached files.

type StreamManagerConfig added in v0.20.0

type StreamManagerConfig interface {
	GetMaxStreamingTranscodeSize() models.StreamingResolutionEnum
	GetLiveTranscodeInputArgs() []string
	GetLiveTranscodeOutputArgs() []string
	GetTranscodeHardwareAcceleration() bool
}

type StreamOptions added in v0.20.0

type StreamOptions struct {
	StreamType *StreamType
	VideoFile  *models.VideoFile
	Resolution string
	Hash       string
	Segment    string
}

type StreamRequestContext added in v0.20.0

type StreamRequestContext struct {
	context.Context
	ResponseWriter http.ResponseWriter
}

func NewStreamRequestContext added in v0.20.0

func NewStreamRequestContext(w http.ResponseWriter, r *http.Request) *StreamRequestContext

func (*StreamRequestContext) Cancel added in v0.20.0

func (c *StreamRequestContext) Cancel()

type StreamType added in v0.20.0

type StreamType struct {
	Name          string
	SegmentType   *SegmentType
	ServeManifest func(sm *StreamManager, w http.ResponseWriter, r *http.Request, vf *models.VideoFile, resolution string)
	Args          func(codec VideoCodec, segment int, videoFilter VideoFilter, videoOnly bool, outputDir string) Args
}

func (StreamType) FileDir added in v0.20.0

func (t StreamType) FileDir(hash string, maxTranscodeSize int) string

func (StreamType) String added in v0.20.0

func (t StreamType) String() string

type TranscodeOptions

type TranscodeOptions struct {
	StreamType StreamFormat
	VideoFile  *models.VideoFile
	Resolution string
	StartTime  float64
}

func (TranscodeOptions) FileGetCodec added in v0.26.0

func (o TranscodeOptions) FileGetCodec(sm *StreamManager, maxTranscodeSize int) (codec VideoCodec)

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 Version added in v0.27.0

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

FFMpeg version params

func (Version) Gteq added in v0.27.0

func (v Version) Gteq(other Version) bool

Gteq returns true if the version is greater than or equal to the other version.

func (Version) String added in v0.27.0

func (v Version) String() string

type VideoCodec added in v0.15.0

type VideoCodec struct {
	Name     string // The full name of the codec including profile/quality
	CodeName string // The core codec name without profile/quality suffix
}

func HLSGetCodec added in v0.20.0

func HLSGetCodec(sm *StreamManager, name string) (codec VideoCodec)

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) ScaleMaxLM added in v0.20.0

func (f VideoFilter) ScaleMaxLM(width int, height int, reqHeight int, maxWidth int, maxHeight int) VideoFilter

ScaleMaxLM scales an image to fit within specified maximum dimensions while maintaining its aspect ratio.

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