mediaserver

package module
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 6 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Media Server 🌇

Go Reference Version Build Status Go Report Card Codecov

On-the-Fly Media Manipulation for Go

Media Server is a media manipulation library that works inside of your existing applications. It manages uploads and downloads, and lets you translate files into different encodings on the fly using FFmpeg. It works primarily with images and audio files, with video manipulations currently under development.


// originals, processed are afero.Fs filesystems; working is a local temp area.
ms := mediaserver.New(originals, processed, working)

// Add an original file
if err := ms.Put("myfile.png", fileData); err != nil {
  // handle error
}

// Describe the processed file you want (resized, transcoded, etc.)
filespec := mediaserver.FileSpec{
  Filename:          "myfile.png",
  OriginalExtension: ".png",
  Extension:         ".webp",
  Width:             600,
  Height:            600,
}

// Serve writes the (cached or freshly processed) file to the HTTP response
if err := ms.Serve(responseWriter, request, filespec); err != nil {
  // handle error
}

Use Process instead of Serve to write the result to any io.Writer, and ServeOriginal to return an unmodified upload.

Image Resizing

Media Server can resize and transcode images. Just request an image with a FileSpec that matches your needs and the corresponding file will be generated (or retrieved from the cache) and returned to your calling application.

// This filespec resizes an image to 1200px (maintaining aspect ratio)
filespec := mediaserver.Filespec{
  Width:1200,
}

Media Transcoding

Media Server can automatically translate files between these formats:

// This filespec converts an audio file into an MP3
filespec := mediaserver.Filespec{
  MimeType:"audio/mp3"
}

Image Types: GIF, JPG, PNG, WEBP

Audio Types: AAC, FLAC, M4A, MP3, OGG, OPUS

Video Types: Coming soon

FFmpeg Dependency

This library now depends on FFmpeg for all media manipulations. This eliminated a problematic dependency on CGo, and has expanded the kinds of media files that mediaserver can manipulate.

Media Server maintains two resource directories: one that contains original uploads and a cache of modified or transcoded files.

Afero Filesystems

Media server uses Afero to connect to both of the file directories (one for originals, and one for cached results). Afero is a filesystem abstraction with connectors for many different kinds of directory services, including:

Pull Requests Welcome

This library is a work in progress, and will benefit from your experience reports, use cases, and contributions. If you have an idea for making Media Server better, send in a pull request. We're all in this together! 🌇

Documentation

Overview

Package mediaserver stores uploaded media files and serves transformed versions of them on demand, using FFmpeg to resize images and transcode audio and video.

A MediaServer works across three filesystems. "original" holds uploads exactly as they arrived. "processed" is a regenerable cache of transformed results, keyed by the FileSpec that produced them. "working" is a local directory of recently served files, evicted after a TTL.

Serve walks those layers in reverse, generating each one only when it is missing. Non-media files are copied through unchanged, so FFmpeg is needed only for image, audio, and video transforms.

Remote cover art is fetched through an SSRF-guarded client; see WithAllowedHosts and WithAllowPrivateIPs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FileSpec

type FileSpec struct {
	Filename          string       // Original filename
	OriginalExtension string       // Original file extension
	Extension         string       // File extension including a dot (.mp3)
	Width             int          // For images and videos, the requested width
	Height            int          // For images and videos, the requested height
	Bitrate           int          // For audio and videos, the audio bitrage
	Metadata          mapof.String // Metadata to add to the outbound file
	Cache             bool         // If TRUE, then allow caching
}

FileSpec represents all the parameters available for requesting a file. This can be generated directly from a URL.

func NewFileSpec

func NewFileSpec() FileSpec

NewFileSpec returns a FileSpec with an initialized Metadata map.

func (*FileSpec) AspectRatio added in v0.11.0

func (filespec *FileSpec) AspectRatio() float64

AspectRatio returns the width/height ratio, or 0 if either dimension is unset.

func (*FileSpec) CacheHeight

func (filespec *FileSpec) CacheHeight() int

CacheHeight returns the height of the file to save in the cache

func (*FileSpec) CacheWidth

func (filespec *FileSpec) CacheWidth() int

CacheWidth returns the width of the file to save in the cache

func (*FileSpec) DownloadFilename added in v0.14.0

func (filespec *FileSpec) DownloadFilename() string

DownloadFilename returns the name that should be used when downloading the file.

func (*FileSpec) MimeCategory

func (filespec *FileSpec) MimeCategory() string

MimeCategory returns the first half of the mime type

func (*FileSpec) MimeType

func (filespec *FileSpec) MimeType() string

MimeType returns the mime type of the requested (output) file.

func (*FileSpec) OriginalMimeCategory added in v0.13.0

func (filespec *FileSpec) OriginalMimeCategory() string

OriginalMimeCategory returns the first half of the original file's mime type.

func (*FileSpec) OriginalMimeType added in v0.13.0

func (filespec *FileSpec) OriginalMimeType() string

OriginalMimeType returns the mime type of the original (source) file.

func (*FileSpec) ProcessedDir added in v0.15.0

func (filespec *FileSpec) ProcessedDir() string

ProcessedDir returns the name of the directory within the cache where versions of this file will be stored.

func (*FileSpec) ProcessedFilename added in v0.15.0

func (filespec *FileSpec) ProcessedFilename() string

ProcessedFilename returns the filename to be used when retrieving this from the FileSpec cache.

func (*FileSpec) ProcessedPath added in v0.15.0

func (filespec *FileSpec) ProcessedPath() string

ProcessedPath returns the complete path (within the cache directory) to the file requested by this FileSpec

func (*FileSpec) Resize

func (filespec *FileSpec) Resize() bool

Resize returns TRUE if the FileSpec is requesting that the file be resized.

func (*FileSpec) WorkingFilename added in v0.15.0

func (filespec *FileSpec) WorkingFilename() string

WorkingFilename returns the filename used for this FileSpec in the working directory.

type MediaServer

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

MediaServer manages files on a filesystem and performs image processing when requested.

func New

func New(original afero.Fs, processed afero.Fs, working *WorkingDirectory, opts ...Option) MediaServer

New returns a fully initialized MediaServer.

func (MediaServer) Delete

func (ms MediaServer) Delete(filename string) error

Delete completely removes a file from the MediaServer along with any cached files. A file whose original is already gone is not an error, so Delete is safe to repeat.

func (MediaServer) Process

func (ms MediaServer) Process(ctx context.Context, filespec FileSpec, output io.Writer) error

Process applies the processing steps in the FileSpec to the original file and writes the result to output, bounded by ctx or by the default timeout when ctx has no deadline.

func (MediaServer) Put

func (ms MediaServer) Put(filename string, file io.Reader) error

Put adds a new file into the MediaServer.

func (MediaServer) Serve added in v0.15.0

func (ms MediaServer) Serve(responseWriter http.ResponseWriter, request *http.Request, filespec FileSpec) error

Serve locates the file, processes it if necessary, and returns it to the caller, reading from (and adding to) the processed cache and the working directory along the way.

func (MediaServer) ServeOriginal added in v0.15.12

func (ms MediaServer) ServeOriginal(responseWriter http.ResponseWriter, _ *http.Request, filename string) error

ServeOriginal returns the original, unprocessed file that was added to the mediaserver

type Option added in v0.16.0

type Option func(*options)

Option configures a MediaServer when it is created with New.

func WithAllowPrivateIPs added in v0.16.0

func WithAllowPrivateIPs(allow bool) Option

WithAllowPrivateIPs controls whether remote cover-image fetches may connect to non-public IP addresses (loopback, private, link-local). The default is FALSE, which blocks them.

func WithAllowedHosts added in v0.16.0

func WithAllowedHosts(hosts ...string) Option

WithAllowedHosts restricts remote cover-image fetches to the named hosts, on top of the private-address block. When no hosts are supplied, any public host is allowed.

type WorkingDirectory added in v0.15.0

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

WorkingDirectory manages files added and removed to the working directory.

func NewWorkingDirectory added in v0.15.0

func NewWorkingDirectory(folder string, ttl time.Duration, capacity int) *WorkingDirectory

NewWorkingDirectory returns a fully initialized WorkingDirectory. It launches a background cleanup goroutine, so the caller must Close it when finished.

func (*WorkingDirectory) Close added in v0.15.0

func (wd *WorkingDirectory) Close()

Close shuts down the working directory, all background processes, and deletes all files from the filesystem

func (*WorkingDirectory) Exists added in v0.15.0

func (wd *WorkingDirectory) Exists(name string) bool

Exists returns TRUE if the file exists in the working directory

func (*WorkingDirectory) Open added in v0.15.0

func (wd *WorkingDirectory) Open(name string) (*os.File, error)

Open loads the file from the working directory and resets the TTL. It is the caller's responsibility to close the file when finished.

func (*WorkingDirectory) Remove added in v0.15.0

func (wd *WorkingDirectory) Remove(name string)

Remove deletes a file from the working directory

func (*WorkingDirectory) RemoveAll added in v0.15.0

func (wd *WorkingDirectory) RemoveAll()

RemoveAll deletes all files from the working directory

func (*WorkingDirectory) RemoveByOriginal added in v0.17.0

func (wd *WorkingDirectory) RemoveByOriginal(original string)

RemoveByOriginal deletes every working file that was generated from the named original file.

func (*WorkingDirectory) Write added in v0.15.0

func (wd *WorkingDirectory) Write(name string, reader io.Reader) error

Write adds a new file into the working directory, and sets a TTL for the file to be deleted

Directories

Path Synopsis
Package ffmpeg runs the ffmpeg command line tool from Go.
Package ffmpeg runs the ffmpeg command line tool from Go.

Jump to

Keyboard shortcuts

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