media

package module
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 11 Imported by: 4 modules, 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

go-media

Test Go Reference

Go bindings for FFmpeg, Chromaprint, libexif, libheif and LibRaw, with higher-level packages for reading, decoding, encoding, filtering and remultiplexing audio and video, and gomedia, a CLI, client and server for probing and encoding media files.

Motivation

The goal isn't to replace ffmpeg, but to provide a programmatic interface for processing audio and video files from Go. go-media supports all the audio and video formats FFmpeg supports, and its bindings for libheif, LibRaw, libexif and Chromaprint are the basis for reading HEIF/AVIF and RAW camera images, EXIF metadata, and audio fingerprints in go-metadata.

Current Status

This module is in development - the API may still change. Implemented so far:

  • FFmpeg-backed audio/video: codecs, formats, filters, pixel/sample formats, audio channel layouts, demuxing/muxing/remuxing, decoding/encoding, filtering and resampling, hardware acceleration (transcoding via the CLI is still TBC)
  • Low-level bindings for Chromaprint, libexif, libheif and LibRaw (sys/)
  • Segmenting decoded audio into fixed-size or silence-separated segments (pkg/segmenter)

Metadata extraction, including EXIF, XMP, HEIF and RAW images, TMDB and AcoustID lookups, has moved to go-metadata, which uses these bindings.

Requirements

Building from source compiles several C/C++ dependencies (FFmpeg, Chromaprint, libexif, LibRaw, libheif) as static libraries before the Go module itself. You'll need a C/C++ toolchain, pkg-config, cmake and nasm, plus the codec libraries you want support for - FFmpeg's own configure step and libheif's CMake step both auto-detect optional codecs via pkg-config, so anything not installed is simply compiled out rather than causing a build failure.

macOS (Homebrew):

# Basic dependencies (required)
brew install pkg-config cmake nasm curl freetype lame opus libvorbis libvpx x264 x265 zvbi

# Recommended, for HEIF/AVIF decoding (libde265, aom, dav1d)
brew install libde265 aom dav1d jpeg

# Optional: homebrew-ffmpeg tap for more FFmpeg codecs
brew tap homebrew-ffmpeg/ffmpeg
brew install homebrew-ffmpeg/ffmpeg/ffmpeg \
  --with-fdk-aac --with-libbluray --with-libsoxr --with-libvidstab \
  --with-libvmaf --with-openh264 --with-openjpeg --with-rav1e \
  --with-srt --with-svt-av1 --with-webp --with-xvid --with-zimg

Debian/Ubuntu:

apt install pkg-config cmake nasm curl build-essential \
  libfreetype-dev libmp3lame-dev libopus-dev libvorbis-dev libvpx-dev \
  libx264-dev libx265-dev libnuma-dev libzvbi-dev \
  libde265-dev libaom-dev libdav1d-dev

Fedora:

dnf install pkg-config cmake nasm curl freetype-devel lame-devel opus-devel \
  libvorbis-devel libvpx-devel x264-devel x265-devel numactl-devel zvbi-devel \
  libde265-devel libaom-devel dav1d-devel

Vulkan Hardware Support (Linux):

# Debian/Ubuntu
apt install libvulkan-dev

# Fedora
dnf install vulkan-loader-devel

Building

git clone https://github.com/mutablelogic/go-media
cd go-media
make              # Builds ffmpeg, chromaprint, libexif, libraw, libheif, then all cmd/* binaries

Static libraries and pkg-config files land in build/install. Once the C dependencies are built, you can rebuild just the Go side:

make cmd/gomedia   # Rebuild the gomedia binary only, reusing the already-built C libraries
Building Manually

If you need to invoke go build/go test yourself rather than through make, set the same CGO environment variables the Makefile uses:

export PKG_CONFIG_PATH="${PWD}/build/install/lib/pkgconfig"
export CGO_LDFLAGS_ALLOW="-(W|D).*"
export CGO_LDFLAGS="-lstdc++ -Wl,-no_warn_duplicate_libraries"  # drop the -Wl,... flag on Linux
go build -o build/gomedia ./cmd/gomedia
Testing
make test           # Build all C deps and run the full Go test suite
make test-sys        # sys/<ffmpeg version> bindings only
make test-ffmpeg      # pkg/ffmpeg/...
make test-chromaprint # pkg/segmenter, sys/chromaprint
make test-exif        # sys/libexif
make test-raw         # sys/libraw
make test-heif        # sys/libheif
make test-gomedia     # task/..., profile/..., gomedia/...

Usage

Command-Line Tool
# Run the server
gomedia run

# Probe a media file, or a URL or device, for its container format, streams and metadata
gomedia probe-media <file>
gomedia probe-source <url>

# Encode a media file into a new format
gomedia encode <file>

# List capabilities
gomedia codecs
gomedia formats
gomedia pixelformats
gomedia sampleformats
gomedia channellayouts
gomedia devices

# Manage audio profiles, and tasks
gomedia audio-profile-create
gomedia tasks
gomedia task-events

Run gomedia --help (or gomedia <command> --help) for the full, current set of flags - this list reflects the commands defined in gomedia/cmd and may grow.

Go API - Probing and Media Management
package main

import (
	"context"
	"fmt"
	"os"

	manager "github.com/mutablelogic/go-media/gomedia/manager"
	schema "github.com/mutablelogic/go-media/gomedia/schema"
)

func main() {
	m, err := manager.New(context.Background())
	if err != nil {
		panic(err)
	}

	f, err := os.Open("video.mp4")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	resp, err := m.Probe(context.Background(), schema.ProbeRequest{Reader: f})
	if err != nil {
		panic(err)
	}

	fmt.Printf("Format: %s\n", resp.Format)
	fmt.Printf("Duration: %.3fs\n", resp.Duration)
	for _, stream := range resp.Streams {
		fmt.Printf("Stream %d\n", stream.Id())
	}
}
Low-Level FFmpeg Bindings

For direct FFmpeg access, use sys/ffmpeg80, selected via the Makefile's SYS_VERSION:

import (
	ff "github.com/mutablelogic/go-media/sys/ffmpeg80"
)

filter := ff.AVFilter_get_by_name("scale")
graph := ff.AVFilterGraph_alloc()
// ... etc

Project Structure

sys/ffmpeg80/                                # Low-level CGO FFmpeg bindings
sys/libheif/, sys/libraw/, sys/libexif/      # Low-level CGO bindings for image metadata/codecs
sys/chromaprint/, sys/dvb/                   # Other low-level bindings

pkg/ffmpeg/          # High-level FFmpeg API (Reader, Decoder, Encoder, Resampler, Frame)
pkg/segmenter/       # Segmenting decoded audio
pkg/sdl/             # SDL2 video/audio player (library only; not wired into the gomedia CLI)

gomedia/
  schema/            # Request/response types for the CLI/API surface
  manager/           # Orchestrates pkg/ffmpeg, profiles and tasks
  cmd/                # kong-based CLI command definitions

cmd/gomedia/          # main() entrypoint, wraps gomedia/cmd via go-server's cmd.Main

Docker

Build a Docker image with all dependencies:

make docker                              # tags ghcr.io/mutablelogic/gomedia:<version>-<os>-<arch>
DOCKER_REPO=docker.io/user/gomedia make docker

For GPU-accelerated encoding/decoding with Vulkan, see Docker GPU Setup for instructions on passing through GPU devices from the host.

License & Distribution

This software is licensed under the Apache License 2.0.

go-media
https://github.com/mutablelogic/go-media/
Copyright (c) 2021-2026 The go-media authors, All rights reserved.

Under the Apache License 2.0, you are free to use, modify, and distribute this software for any purpose, including commercial applications. You may statically or dynamically link to this library without affecting your own code's license. Attribution requirement: When redistributing this software or derivative works (in source or binary form), you must include the copyright notice above, and a copy of the LICENSE and NOTICE files. If you modify the code, you must state your changes. See the Apache License 2.0 for complete terms.

Important: When distributing binaries that include this software, you must also comply with the licenses of the libraries it links to, as described below. Their copyright notices and licenses are in the NOTICE file.

Library License
FFmpeg GPL 3.0 or later, as the Makefile builds it (see below); LGPL 2.1 or later by default
libexif LGPL 2.1 or later
libheif LGPL 3.0
LibRaw LGPL 2.1 or CDDL 1.0, with bundled code under BSD and MIT licenses
Chromaprint LGPL 2.1, as it includes parts of FFmpeg; its own code is MIT
FFmpeg as built by the Makefile

The Makefile configures FFmpeg with --enable-gpl and --enable-version3, for x264, x265 and OpenSSL 3, which FFmpeg's configure reports as "GPL version 3 or later" (it's FFMPEG_LICENSE in build/ffmpeg-<version>/config.h). A binary which includes it is licensed under the GNU GPL v3, so distributing it means providing its complete source code under the GPL v3. go-media's own Apache 2.0 code is compatible with that.

make FFMPEG_NONFREE=1 also enables the nonfree components, fdk-aac and libtls, when they're found. FFmpeg reports such a build as "nonfree and unredistributable", so a binary built with it is for your own use only. For an LGPL build of FFmpeg, configure it without --enable-gpl, or link to a build of FFmpeg whose license suits you, such as one from your Linux distribution.

LGPL Notice

This software also statically links to libexif, libheif, LibRaw and Chromaprint, which are licensed under the LGPL: v2.1, except libheif, which is v3 (LibRaw is also available under the CDDL).

LGPL Compliance: Under the LGPL, you may:

  • Use this software for commercial or non-commercial purposes
  • Distribute this software in its compiled form
  • Modify the go-media source code under Apache 2.0

Requirements when distributing binaries:

  1. Include the NOTICE file, the LGPL licenses, and a copy of the GNU GPL v3, which LGPL v3 (libheif) requires alongside it
  2. Provide access to the source code of the libraries used (available in build/ after building, such as build/ffmpeg-8.0.3/ - check the Makefile's *_VERSION variables for the exact versions), and, as FFmpeg is GPL, of the whole binary
  3. Allow users to relink the application with modified versions of the libraries

The source code of the libraries is automatically downloaded during the build process. See Makefile for details.

Contributing

Please file feature requests and bugs at github.com/mutablelogic/go-media/issues. Pull Requests are welcome, after discussion of the proposed changes.

References

Documentation

Index

Constants

View Source
const (
	// MetaArtwork is the metadata key for artwork (album art, cover art, etc.)
	MetaArtwork = "artwork"

	// MetaChapter is the metadata key for a chapter marker. Unlike other
	// metadata, which is a single container-level entry per key, a Metadata
	// slice can hold multiple MetaChapter entries - one per chapter, in
	// order - the same way multiple attached-pic streams yield multiple
	// MetaArtwork entries. Each entry's Any() returns a Chapter.
	MetaChapter = "chapter"

	// MetaMarkdown is the namespace of a document's content as Markdown,
	// which handlers only return when it's requested, as converting a
	// document can be expensive. Its keys are body, offset and next (see
	// metadata.WithRange).
	MetaMarkdown = "markdown"
)

Variables

This section is empty.

Functions

func FileProtocolPath added in v1.9.5

func FileProtocolPath(u *url.URL) string

FileProtocolPath returns the raw filesystem path to hand to FFmpeg's file protocol, from a parsed "file" scheme URL. FFmpeg's file protocol only strips the literal "file:" prefix (libavformat/file.c: av_strstart(url, "file:", &url)) - it does no further URI parsing at all, so whatever follows the colon must already be a usable OS path.

RFC 8089's standard form for a local Windows path, file:///C:/dir/file (an empty authority, then a path that still carries the leading "/" before the drive letter), parses in Go to Path="/C:/dir/file" - passed straight through, that leading slash makes it an invalid Windows path ("No such file or directory"), so it's stripped here when present.

A non-empty, non-"localhost" Host is a UNC path, file://server/share/file (Host="server", Path="/share/file") - FFmpeg's file protocol expects this reassembled as "//server/share/file", so the host is preserved rather than silently dropped.

The opaque form some callers may already send directly (file:C:/dir/file or file:/tmp/file, no "//") bypasses all of this: u.Opaque already holds exactly the right string.

func HTTPErr added in v1.9.2

func HTTPErr(err error) error

Types

type Chapter added in v1.9.2

type Chapter struct {
	Start    time.Duration
	End      time.Duration
	Metadata map[string]string
}

Chapter describes a single chapter marker: its position in the container and its own metadata tags (an AVChapter carries its own AVDictionary, distinct from the container's - usually just "title", but not limited to it). It's the value returned by a MetaChapter entry's Any() method.

type Err added in v1.7.2

type Err uint
const (
	ErrBadParameter   Err = http.StatusBadRequest
	ErrNotFound       Err = http.StatusNotFound
	ErrInternalError  Err = http.StatusInternalServerError
	ErrNotImplemented Err = http.StatusNotImplemented
)

func (Err) Code added in v1.7.2

func (code Err) Code() uint

func (Err) Error added in v1.7.2

func (code Err) Error() string

func (Err) HTTP added in v1.9.2

func (e Err) HTTP() httpresponse.Err

func (Err) With added in v1.7.2

func (code Err) With(args ...any) error

func (Err) Withf added in v1.7.2

func (code Err) Withf(format string, args ...any) error

type Metadata added in v1.5.1

type Metadata interface {
	// Return the metadata key (may include ns:name, e.g., "exif:DateTimeOriginal")
	Key() string

	// Return the value as a string. Returns the mimetype
	// if the value is a byte slice, and the mimetype can be
	// detected.
	Value() string

	// Returns the value as a byte slice
	Bytes() []byte

	// Returns the value as an image
	Image() image.Image

	// Returns the value as an interface
	Any() any
}

Metadata is a key/value pair which can be used to describe a media object or other metadata. The value can be retrieved as a string value, data, or other type. If the value is a byte slice, then it can also be retrieved as an image (for artwork)

type NamedReader added in v1.9.2

type NamedReader interface {
	io.Reader
	Name() string
}

NamedReader is an interface that extends io.Reader with a Name() method

type NamedWriter added in v1.9.2

type NamedWriter interface {
	io.Writer
	Name() string
}

NamedWriter is an interface that extends io.Writer with a Name() method

type Type added in v1.6.7

type Type int

Type of codec, device, format or stream

const (
	NONE     Type = 0           // Type is not defined
	VIDEO    Type = (1 << iota) // Type is video
	AUDIO                       // Type is audio
	SUBTITLE                    // Type is subtitle
	DATA                        // Type is data
	UNKNOWN                     // Type is unknown
	INPUT                       // Type is input format
	OUTPUT                      // Type is output format
	DEVICE                      // Type is input or output device

	ANY = NONE // Type is any (used for filtering)
)

func (Type) FlagString added in v1.6.7

func (t Type) FlagString() string

Return a flag as a string

func (Type) Is added in v1.6.7

func (t Type) Is(u Type) bool

Returns true if the type matches a set of flags

func (Type) MarshalJSON added in v1.6.7

func (t Type) MarshalJSON() ([]byte, error)

Return the type as a string

func (Type) String added in v1.6.7

func (t Type) String() string

Return the type as a string

Directories

Path Synopsis
_old
testcard
Package testcard implements a default gomedia/schema.Source: a generated sine wave tone, suitable as a fallback for a live encoding job when no other source is available.
Package testcard implements a default gomedia/schema.Source: a generated sine wave tone, suitable as a fallback for a live encoding job when no other source is available.
cmd
gomedia command
etc
gomedia
cmd
pkg
sdl
Package sdl provides SDL2-based audio and video output for go-media.
Package sdl provides SDL2-based audio and video output for go-media.
segmenter
Package segmenter provides audio segmentation functionality.
Package segmenter provides audio segmentation functionality.
profile
cmd
sys
chromaprint
This package provides chromaprint audio fingerprinting bindings
This package provides chromaprint audio fingerprinting bindings
dvb
DVB (Digital Video Broadcasting) bindings for Go
DVB (Digital Video Broadcasting) bindings for Go
ffmpeg80
The low-level ffmpeg bindings for ffmpeg version 8.0.
The low-level ffmpeg bindings for ffmpeg version 8.0.
task
cmd

Jump to

Keyboard shortcuts

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