g@m8sh.su 1e583508da fix(build): rebuild vendored libs on a glibc 2.35 baseline
The vendored archives were compiled on a current toolchain and carried baked-in __isoc23_strtol references (glibc >= 2.38 only), so every binary linking gopeg inherited a glibc 2.38 floor — and linking on a glibc 2.44 host stamped 2.44 outright. Both linux targets are rebuilt inside ubuntu:22.04 (recipe aom-x265-2): amd64 keeps only the libmvec _ZGV pair (2.35 floor), arm64 is fully clean. The builder also fixes two portability bugs found on the way: meson libdir is forced to lib (Debian-family defaults to lib64, the install layout reads lib/), and cross cmake now sets CMAKE_CXX_COMPILER (aom app binaries linked with the host c++ on distro toolchains, failing the aarch64 build).

Assisted-by: Cline:GLM-4.6
2026-11-13 14:29:21 +03:00
2026-06-07 10:00:34 +03:00
2026-10-18 19:39:47 +03:00
2026-06-07 00:40:27 +03:00
2026-06-07 00:40:27 +03:00
2026-06-07 00:40:27 +03:00
2026-10-18 19:39:47 +03:00
2026-10-18 19:39:47 +03:00
2026-10-18 19:39:47 +03:00
2026-06-07 00:40:27 +03:00
2026-11-09 21:54:59 +03:00
2026-06-07 00:40:27 +03:00
2026-06-07 00:40:27 +03:00
2026-06-06 18:04:56 +00:00
2026-10-18 19:39:47 +03:00

gopeg banner

gopeg

Go video library with no runtime dependencies — decode and encode video/audio. FFmpeg, dav1d, libvpx, libaom and libx265 are statically linked: import the package and get a single binary, no system installs required.

Installation

go get m8sh.su/x/gopeg

Requires CGO and a C compiler:

# arch/manjaro
sudo pacman -S gcc

# debian/ubuntu
sudo apt install gcc

Platforms

Platform Arch Status
linux/amd64 x86_64 ✅ Supported
linux/arm64 AArch64 ✅ Supported
windows/amd64 x86_64 ✅ Supported
darwin/amd64 x86_64 ✅ Supported
darwin/arm64 Apple Silicon ✅ Supported
web/wasm wasm32 🚧 Coming soon

Supported formats

Decoding Encoding
Video H.264, H.265/HEVC, AV1, VP9, VP8, MPEG-4, FFV1 VP9, VP8 (libvpx), H.265/HEVC (libx265), AV1 (libaom), MPEG-4, FFV1
Audio AAC, MP3, Opus, Vorbis, FLAC, PCM AAC, Opus, FLAC
Images PNG, JPEG, WebP, GIF (animated), AVIF PNG (lossless, alpha), JPEG, GIF (animated, 256-color)
Containers MP4, MKV, WebM, AVI, FLV, OGG, IVF, MPEGTS MP4, MKV, WebM, AVI, OGG, FLAC, ADTS

Still images decode as single-frame videos (one VideoFrame with an NRGBA image), so NewDecoder/DecodeFrame work on PNG/JPEG/WebP/GIF/AVIF files as-is. AVIF decoding rides the AV1 decoder (dav1d); AVIF/WebP encoding would require libaom/libwebp external libraries and is not part of the build — PNG and lossless-oriented formats cover the lossless case.

Features

  • Decode video frames as image.NRGBA — standard Go image type, no conversion needed
  • Decode audio frames as []float32 interleaved PCM
  • Decode still images (PNG, JPEG, WebP, GIF, AVIF) as one-frame videos
  • Encode video (VP9/VP8/H.265/AV1/MPEG-4/FFV1) and audio (AAC/Opus/FLAC) from plain Go types
  • Encode images: PNG (lossless incl. alpha), JPEG, animated GIF with in-Go median-cut palette quantization
  • Encode animated AVIF (Format: "avif" + CodecAV1): infinitely looping "avis" image sequences with a real alpha channel — the matte rides the AVIF auxiliary track (darwin builds without libaom report it unavailable via HasEncoder)
  • Crossfade rebuilds a clip so it loops seamlessly: the tail dissolves into the opening frames
  • Convert any decodable video to an animated GIF with ToGIF (scaling, FPS decimation, palettes handled for you)
  • Extract audio tracks losslessly with ExtractAudio (stream copy when codecs fit, re-encode otherwise) and the adts container
  • Transparent video: encode PNG-style alpha into VP9/VP8/FFV1 WebM/MKV (VideoEncodeOptions.Alpha) and decode it back, including the WebM alpha substream produced by external tools
  • Automatic pixel-format conversion and scaling via swscale; audio resampling via swresample
  • Read from / write to any io.Reader / io.Writer — files, in-memory buffers, HTTP streams, pipes
  • Seeking supported when the reader implements io.Seeker; works without it too (fragmented MP4)
  • Zero runtime dependencies — all FFmpeg, dav1d, libvpx, libaom and libx265 libs statically linked
  • Single go build for all supported platforms

Quick start

package main

import (
    "fmt"
    "image/png"
    "os"

    "m8sh.su/x/gopeg"
)

func main() {
    f, _ := os.Open("video.mp4")
    defer f.Close()

    dec, err := gopeg.NewDecoder(f)
    if err != nil {
        panic(err)
    }
    defer dec.Close()

    meta := dec.Meta()
    fmt.Printf("duration: %.2fs\n", meta.Duration.Seconds())
    fmt.Printf("video: %dx%d %s @ %d/%d fps\n",
        meta.Video.Width, meta.Video.Height,
        meta.Video.CodecName,
        meta.Video.FPSNum, meta.Video.FPSDen)
    if meta.Audio != nil {
        fmt.Printf("audio: %dHz %dch %s\n",
            meta.Audio.SampleRate,
            meta.Audio.Channels,
            meta.Audio.CodecName)
    }

    for {
        frame, err := dec.DecodeFrame()
        if err != nil {
            panic(err)
        }
        if frame == nil {
            break // EOF
        }
        if frame.Video != nil {
            f, _ := os.Create("frame.png")
            png.Encode(f, frame.Video.Img)
            f.Close()
        }
        if frame.Audio != nil {
            fmt.Printf("audio pts=%v samples=%d\n",
                frame.Audio.PTS,
                len(frame.Audio.Samples)/frame.Audio.Channels)
        }
    }
}

API

// Open a decoder from any reader. If r also implements io.Seeker,
// FFmpeg will use it for random access where the format requires it.
func NewDecoder(r io.Reader) (*Decoder, error)

// Returns duration, video/audio stream info. Safe to call before decoding.
func (d *Decoder) Meta() Meta

// Decode the next video or audio frame. Returns nil, nil on EOF.
// Frame.Video and Frame.Audio are mutually exclusive per call.
func (d *Decoder) DecodeFrame() (*Frame, error)

// Release all FFmpeg resources. Safe to call multiple times.
func (d *Decoder) Close()

// Open an encoder writing into any writer. Format is a container
// name ("mp4", "webm", "avi", "ogg", ...). If w implements io.Seeker
// the muxer may use it; without seeking, fragmented/streamable
// variants are chosen automatically.
func NewEncoder(w io.Writer, opts EncoderOptions) (*Encoder, error)

// Encode one video frame (image.NRGBA). A negative pts auto-numbers
// frames from the configured frame rate.
func (e *Encoder) WriteVideo(img *image.NRGBA, pts time.Duration) error

// Encode interleaved float32 PCM samples. Channel count and sample
// rate must stay constant across calls.
func (e *Encoder) WriteAudio(samples []float32, channels, sampleRate int, pts time.Duration) error

// Flush buffered frames, finalize the container and free all
// resources. Idempotent.
func (e *Encoder) Close() error

// Reports whether a codec is available in the vendored build, e.g.
// HasEncoder(CodecVP9). Use it to skip work on reduced builds.
func HasEncoder(codec VideoCodec) bool

// Stream-copy remux from any reader into any writer. No decoding or
// re-encoding: packets and codec configuration move untouched, so
// quality and alpha survive. Only the first video stream is copied by
// default — audio, subtitle and cover-art tracks are dropped (set
// RemuxOptions.Audio to also keep the first audio stream). The
// audio-only formats "adts", "ogg" and "flac" copy just the audio
// track, which turns Remux into lossless audio extraction for codecs
// the target container can carry (AAC -> adts, Opus/Vorbis -> ogg,
// FLAC -> flac).
func Remux(r io.Reader, w io.Writer, opts RemuxOptions) error

// Extract the audio track of any input: stream-copied when the source
// codec fits the target container (bit-exact, no re-encode), decoded
// and re-encoded through the regular pipeline otherwise.
func ExtractAudio(r io.Reader, w io.Writer, opts ExtractAudioOptions) error

// Convert any decodable video into an animated GIF: frames are
// rescaled, decimated to the requested FPS and quantized to 256-color
// palettes (median cut; alpha thresholded to transparent/opaque).
func ToGIF(r io.Reader, w io.Writer, opts GIFOptions) error

Encoding quick start

var buf bytes.Buffer
e, err := gopeg.NewEncoder(&buf, gopeg.EncoderOptions{
    Format: "webm",
    Video:  gopeg.VideoEncodeOptions{Codec: gopeg.CodecVP9, FPSNum: 30, FPSDen: 1},
    Audio:  gopeg.AudioEncodeOptions{Codec: gopeg.CodecOpus}, // optional
})
if err != nil {
    panic(err)
}
defer e.Close()

e.WriteVideo(myNRGBAFrame, -1)          // auto pts from FPS
e.WriteAudio(pcmFloat32, 2, 48000, 0)

if err := e.Close(); err != nil { // always check Close: it flushes
    panic(err)
}

Transparent video

NRGBA frames carry an alpha channel (RGBA PNGs decode straight into it). To keep it through encoding — transparent overlays, stickers, animations converted from PNGs by any external tool — set Alpha: true:

e, err := gopeg.NewEncoder(&buf, gopeg.EncoderOptions{
    Format: "webm", // "matroska" works too; mp4 cannot carry alpha
    Video:  gopeg.VideoEncodeOptions{Codec: gopeg.CodecVP9, Alpha: true},
})
// ...
for _, img := range transparentNRGBAFrames { // *image.NRGBA from image/png
    e.WriteVideo(img, -1)
}

Frames are encoded as YUVA420P. Supported codecs: VP9, VP8 and lossless FFV1; other codecs and containers are rejected up front by NewEncoder.

Decoding needs no option: VP8/VP9 alpha in WebM/Matroska (including files produced by external tools, where alpha rides in a Matroska BlockAdditional substream) and in-band FFV1 alpha both decode back into the NRGBA alpha channel. Without Alpha on the encode side transparency is discarded, exactly like an opaque source.

Images, GIFs & audio extraction

Still images are just single-frame videos — decode them with NewDecoder:

d, _ := gopeg.NewDecoder(bytes.NewReader(avifBytes)) // PNG, JPEG, WebP, GIF, AVIF
f, _ := d.DecodeFrame() // f.Video.Img is the *image.NRGBA picture

Convert between image formats by decoding one frame and re-encoding it — Format: "png", "jpeg" or "gif" writes a raw image stream:

e, _ := gopeg.NewEncoder(&out, gopeg.EncoderOptions{Format: "png"}) // lossless
e.WriteVideo(f.Video.Img, 0) // add Video.Alpha:true to keep the alpha channel
e.Close()

Animated GIFs are videos too: write several frames (they are quantized to 256-color palettes automatically, alpha thresholded), or convert a whole clip in one call:

err := gopeg.ToGIF(bytes.NewReader(videoBytes), &out, gopeg.GIFOptions{
    Width: 480, Height: 270, FPS: 12,
})

Eject the audio track of any file — lossless stream copy when the codec fits the container, transparent re-encode otherwise:

// AAC source -> raw .adts stream, bit-exact copy (no re-encoding)
err := gopeg.ExtractAudio(bytes.NewReader(mp4Bytes), &out, gopeg.ExtractAudioOptions{})

// Any source -> Opus in Ogg, re-encoded at 96 kbit/s
err = gopeg.ExtractAudio(bytes.NewReader(anything), &out, gopeg.ExtractAudioOptions{
    Codec:   gopeg.CodecOpus,
    BitRate: 96_000,
})

Types

type Meta struct {
    Duration time.Duration
    Video    *VideoMeta  // nil if no video stream
    Audio    *AudioMeta  // nil if no audio stream
}

type VideoMeta struct {
    Width, Height int
    FPSNum, FPSDen int
    CodecName string
}

type AudioMeta struct {
    SampleRate int
    Channels   int
    CodecName  string
}

type Frame struct {
    Video *VideoFrame
    Audio *AudioFrame
}

type VideoFrame struct {
    Img      *image.NRGBA
    PTS      time.Duration
    Duration time.Duration
}

type AudioFrame struct {
    Samples    []float32  // interleaved
    Channels   int
    SampleRate int
    PTS        time.Duration
}

Logging

Logging is disabled by default: the library and the FFmpeg libraries underneath it print nothing. To inspect what FFmpeg is doing, install a logger; the verbosity defaults to LogInfo (FFmpeg's own default) and can be tuned with SetLogLevel:

gopeg.SetLogger(func(level gopeg.LogLevel, context, message string) {
    log.Printf("[gopeg] %s %s: %s", level, context, message)
})
defer gopeg.SetLogger(nil) // restore silent default

gopeg.SetLogLevel(gopeg.LogWarning) // only warnings and worse

Levels mirror FFmpeg's AV_LOG_* constants (LogQuiet, LogPanic, LogFatal, LogError, LogWarning, LogInfo, LogVerbose, LogDebug, LogTrace); lower numeric values are more severe. The logger is process-global, affects all Encoder and Decoder instances, and may be called from FFmpeg worker threads - it must be safe for concurrent use.

For the popular logging libraries gopeg provides ready-made adapters; nil (even a typed nil such as (*logrus.Logger)(nil)) always disables logging again and keeps the library silent:

// log/slog: contexts become attributes, severity becomes slog levels
gopeg.SetSlogLogger(slog.Default())
defer gopeg.SetSlogLogger(nil)

// standard library
gopeg.SetStdLogger(log.Default())
defer gopeg.SetStdLogger(nil)

// logrus, zap's SugaredLogger, or anything else with the
// Debugf/Infof/Warnf/Errorf methods - no dependency required
gopeg.SetLeveledLogger(logrus.StandardLogger())
defer gopeg.SetLeveledLogger(nil)

SetLeveledLogger accepts a small duck-typed interface (LevelLogger) that logrus, zap and friends already satisfy, so gopeg itself stays dependency-free. FFmpeg severity maps onto the closest level the target library offers; distinctions the target cannot express (for example FFmpeg's Verbose vs Debug) are preserved by slog as a ffmpeg_level attribute and by the stdlib logger in the tag itself ([VERBOSE], [INFO ], ...). Anything with a different shape (zerolog, logr, ...) plugs in through SetLogger with a one-line closure, as shown at the top of this section.

Building from source

The libs/ directory contains prebuilt static libraries for all supported platforms. To rebuild from scratch, delete libs/ and use the build script:

make libs          # or: go run cmd/build/main.go

Static libraries built before image support (PNG/JPEG/WebP/GIF decode, PNG/JPEG/GIF encode, AVIF decode) lack those codecs. HasEncoder reports false for them and NewEncoder returns a "not available in this build" error; rebuild the vendored libraries with make libs to pick them up. macOS builds must be refreshed on a macOS host (clang -arch).

The script clones the necessary repositories (dav1d, FFmpeg, libvpx and x265 mirrors) and builds them into static libraries for CGO linking. It is self-contained and needs no root:

  • meson/ninja (dav1d) are bootstrapped into .build/tools when missing (meson from its sdist via python3, ninja from the official static binary).
  • nasm is bootstrapped for x86 targets when missing.
  • On Arch/Manjaro the cross toolchains for linux/arm64 and windows/amd64 are bootstrapped into .build/toolchain by downloading the distro's cross-gcc packages and relocating them with an explicit --sysroot; if a prefixed compiler (e.g. aarch64-linux-gnu-gcc, x86_64-w64-mingw32-gcc) is already on PATH it is used as-is.

So on Arch/Manjaro a bare make libs produces linux/amd64, linux/arm64 and windows/amd64 in one go. On other distros install the cross compilers first:

# debian/ubuntu
sudo apt install gcc meson ninja-build nasm perl gcc-aarch64-linux-gnu gcc-mingw-w64-x86-64

Targets whose toolchain cannot be found are skipped with a notice. macOS hosts build darwin/arm64 and darwin/amd64 natively via clang -arch.

License

GPLv3 - this is free software. Contributions are welcome, feel free to open an issue.

S
Description
Go video encoding/decoding solution
Readme GPL-3.0
591 MiB
0 Stars 1 Watchers 0 Forks
2026-06-06 23:42:09 +00:00
Languages
C 85.4%
Go 14.2%
C++ 0.4%