Skip to content

Media ​

Video encoding ​

gpu.Encoder encodes H.264 and H.265 on the device's hardware: its Vulkan video queue if that encodes the codec, else its VA-API driver (needs libva). Backend reports VulkanVideo or VAAPI.

go
package main

import (
	"log"
	"slices"
	"time"

	"github.com/stubbedev/lys/lib/fourcc"
	"github.com/stubbedev/lys/lib/gpu"
)

func main() {
	dev, err := gpu.Open()
	if err != nil {
		log.Fatal(err)
	}
	defer dev.Close()
	if !slices.Contains(dev.Codecs(), gpu.H264) {
		log.Fatal("this device does not encode H.264")
	}

	enc, err := dev.NewEncoder(gpu.EncoderConfig{
		Codec:       gpu.H264,
		Width:       1920,
		Height:      1080,
		FrameRate:   60,
		KeyInterval: 120,
		QP:          20,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer enc.Close()

	modifiers, err := dev.ExportModifiers(fourcc.ARGB8888)
	if err != nil {
		log.Fatal(err)
	}
	frame, err := dev.NewBuffer(1920, 1080, fourcc.ARGB8888, modifiers)
	if err != nil {
		log.Fatal(err)
	}
	defer frame.Close()

	packets, err := enc.Encode(frame, time.Second/60)
	if err != nil {
		log.Fatal(err)
	}
	rest, err := enc.Flush()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("%s: %d packets", enc.Backend(), len(packets)+len(rest))
}

EncoderConfig:

FieldEffect
CodecH264 or H265
Width, HeightFrame size (after Transform)
FrameRateNominal rate, for the stream's level; frames may arrive at any time
KeyIntervalFrames between keyframes
SourceRegion of the buffer to read; zero reads all of it
TransformThe captured output's wl_output transform, undone by the encoder
QPConstant quantiser, 0 (best) to 51, coded at the encoder's finest where it is finer (Intel's iHD VA-API driver quantises H.265 at 10 at least, and the stream says so). Devices without constant-QP coding use a bitrate matching QP 20 on desktop content
  • The source is a Buffer; pass frame.Dmabuf() to capture to fill it.
  • A compute pass crops, rotates, draws the overlay (SetOverlay) and converts to NV12. It is a submission of the device like a pass, and the Vulkan video queue encodes after it on the GPU, by a timeline semaphore.
  • The buffer is its writer's again when Encode returns. The conversion that reads it leaves its fence on the buffer's dmabuf, which whoever writes the next frame into it under linux-dmabuf's implicit synchronization (a compositor's screencopy) waits for, so Encode waits for nothing. Where no fence tells the writer (NVIDIA's driver, a device without sync_file semaphores) Encode waits for the conversion instead, as it does for the VA-API driver, which takes no semaphore. A writer drawing with this package (a Pass into an ImportTarget of the buffer, as lys-wm's screencopy does) waits for that fence on the GPU, and the conversion waits on the GPU for the fence the writer left, so neither hands the buffer over by waiting.
  • A packet collected before a conversion or an encode that then fails comes out of the next Encode or Flush.
  • Every wait is bounded by the device's wait limit, the VA-API driver's for a picture too: a hung GPU is an error instead of a frozen caller. A wait that runs out is ErrTimeout, and the frame stays in flight: its slot is not reused until a later Encode or Flush has waited for it and returned its packet. Close waits for the frames the VA-API driver is still encoding within the same limit; past it Close returns ErrTimeout and leaves the driver's display open with the surfaces and buffers it may still use, leaked rather than destroyed underneath it.
  • An Encoder belongs to one goroutine.
  • NewEncoder fails with ErrNoVideoEncoder, carrying both backends' reasons, when neither encodes the codec.
  • Each Packet is one Annex-B access unit without parameter sets. ParameterSets returns them as NAL units without start codes (SPS and PPS for H.264; VPS, SPS and PPS for H.265), the form media/mux takes.

Video decoding ​

gpu.VideoDecoder decodes H.264, H.265, AV1 and VP9 on the device's Vulkan video decode queue, the device the renderer draws with. It takes demux packets in decode order and hands out frames in presentation order, each drawn by a Pass (DrawFrame) through its YCbCr conversion: the picture never leaves the GPU.

go
package main

import (
	"errors"
	"io"
	"log"

	"github.com/stubbedev/lys/lib/gpu"
	"github.com/stubbedev/lys/lib/media/demux"
)

func main() {
	dev, err := gpu.Open()
	if err != nil {
		log.Fatal(err)
	}
	defer dev.Close()
	file, err := demux.OpenFile("clip.mp4")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	track := file.Tracks()[0]
	dec, err := dev.NewVideoDecoder(track)
	if errors.Is(err, gpu.ErrNoVideoDecoder) {
		log.Fatal(file.Unsupported(track.Index))
	}
	if err != nil {
		log.Fatal(err)
	}
	defer dec.Close()
	if err := file.Select(track.Index); err != nil {
		log.Fatal(err)
	}
	show := func() {
		for frame := dec.Next(); frame != nil; frame = dec.Next() {
			// pass.DrawFrame(frame, ...) at frame.PTS().
			frame.Release()
		}
	}
	for {
		p, err := file.ReadPacket()
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		if err := dec.Decode(p); err != nil {
			log.Fatal(err)
		}
		show()
	}
	dec.Flush()
	show()
}
  • VideoFrame.ReadRGBA(size) draws a held frame (colour-converted and scaled on the GPU) into an offscreen target and reads that back as RGBA, so a thumbnail moves only its own pixels, not the full-size planes; media.KeyframeImage decodes the keyframe at or before a time and returns it read back this way.
  • DecodeCodecs lists what the device decodes. NewVideoDecoder fails with ErrNoVideoDecoder, naming the codec and why, for any other; lavapipe decodes nothing.
  • Decode takes one packet (an access unit; an AV1 temporal unit or a VP9 superframe, whose hidden frames it decodes too). Next returns the next frame in presentation order, or nil until more packets complete one. Flush at the end of the track hands out the frames held back for reordering.
  • Decode submits a packet's pictures and makes room for more in flight (up to 16) instead of waiting for the GPU. Busy says, without waiting, whether the GPU is four pictures or more behind: a player that holds its next packet back until its loop's next turn while Busy never has Decode wait.
  • Nothing waits on the CPU for a decode. Next hands a frame out while its picture may still be decoding, and the pass that draws it waits for the decode on the GPU: the decode queue signals a timeline semaphore the pass's submission waits for. What waits for that pass (Finish, a CPU read, Publish on a device whose dmabufs carry no fence) then waits for the decode too; VideoFrame.Decoded says, without waiting, whether the decode has finished, for a caller that must not stall there. A device decodes only where it has timeline semaphores.
  • A frame carries its packet's PTS and Duration, its picture's Size with the stream's cropping applied, and its FieldOrder. Pass.DrawFrame draws a region of the picture, given in the picture's own pixels, as DrawTexture draws a texture's; the codec's padding around the picture is out of its reach. The YCbCr matrix, range and chroma siting come from the stream's VUI, AV1 colour config or VP9 colour space (an unnamed matrix is BT.709 from 720 lines up, BT.601 below; a VP9 stream's lines are its render size's, which a stream that resizes its frames keeps). An AV1 frame's Size is its render size where that crops the frame, else the frame's; a VP9 frame's is the frame's, which changes where the stream resizes. Pictures are luma and a plane of interleaved chroma in the stream's depth and chroma format: NV12 for 8-bit 4:2:0, P010 (G10X6_B10X6R10X6_2PLANE_420) for 10-bit, and the 12-bit and 4:4:4 formats of the same family, drawn through the sampler's YCbCr conversion where the device's conversion samples the format with the stream's chroma siting. Where it does not (Intel's lists no conversion for P010, P012 or the 10- and 12-bit 4:4:4 formats) and the frame is a copy, a view of each plane in a plain format (R16, R16G16) is sampled and converted in the shader, as an imported YUV dmabuf is; a device that decodes into separate output pictures it cannot sample so is refused the stream with ErrNoVideoDecoder.
  • A frame's texture belongs to the decoder and is never handed out, so nothing can update or close it: Release hands the frame back, and the decoder decodes into it again once the passes that drew it, the open one too, have finished. Up to 8 frames may be held beside the ones held for reordering and the AV1 and VP9 frames decoded hidden to be shown later; Close releases them all, and a pass refuses a frame released or of a closed decoder.
  • To seek, Reset the decoder, Seek the file and decode from the keyframe, dropping frames before the target. Decoding starts at an IDR or I picture (H.264), an IRAP picture (H.265) or a key frame (AV1 and VP9, from the first packet marked a keyframe); pictures before it, and leading pictures that predict from before it (open-GOP B-frames, RASL pictures), are dropped.
  • Streams decode bit-exactly as ffmpeg decodes them: H.264 Baseline, Main, High and Extended where it keeps to Main (B-frames, reference marking, every picture order count type, scaling matrices, slices, gaps in frame_num, interlaced frames and fields), H.265 Main and Main 10 (reference picture sets in the SPS or slice headers, long-term pictures, CRA starts, slices, wavefronts, scaling lists), AV1 Main at 8 and 10 bits (hidden frames shown by later frame headers, all seven references, compound and skip modes, tiles, 64x64 and 128x128 superblocks, segmentation, delta q and loop filter, CDEF, loop restoration, global motion, error resilient frames, screen content tools; libaom and SVT-AV1 streams), and VP9 profiles 0 and 2 at 8 and 10 bits (hidden alternate reference frames in superframes, all three references, segmentation with temporal prediction and cyclic refresh, tile columns, error resilient and lossless frames, odd sizes, frames predicted from references of another size, intra-only frames; libvpx streams in WebM and MP4), and, where the device decodes them (NVIDIA does), 12-bit H.265 and VP9 profile 2 and 4:4:4 H.265 at 8, 10 and 12 bits (the format range extensions). AV1 frames of other sizes than their references decode, as do superres key frames and the frames predicted from them; superres frames that predict from references are errors that say so (NVIDIA's Vulkan driver decodes them otherwise than dav1d), as are frames smaller than the device decodes (NVIDIA decodes AV1 from 128x128, H.265 from 144x144). The tests decode ffmpeg's frames on one thread: with frame threads its H.264 decoder (9.0.2) shows a field without its frame's other at some thread counts (9, its default on 8 cores), into a frame it shows twice, and on one thread none.
  • Interlaced H.264 comes out as it is coded, a frame's two fields woven into one picture, the top field its even lines: nothing deinterlaces. VideoFrame.FieldOrder says whether a frame is two fields and which is the earlier (Progressive, TopFieldFirst, BottomFieldFirst), for a caller that deinterlaces or tells its output: a frame coded as two field pictures or as field and frame macroblock pairs (MBAFF) is two fields, the earlier the one of the lower picture order count, the top field where they are equal, as ffmpeg says of it; the picture timing SEI is not read. A field picture is a decode of its own into its frame's DPB slot, which the device holds with the fields' lines interleaved; the frame goes to Next when its second field has decoded, whether a packet holds both fields (MP4) or one (a transport stream), with the first field's PTS; each field decodes with the parameter sets before it in the packet, which a stream may change between the two. A field whose frame's other field never comes is decoded for the pictures that predict from it and never shown, as ffmpeg shows none. Reference marking is by field (8.2.5): the sliding window, and memory management control operations that name single fields. A packet of both fields whose second fails (every frame held, say) leaves the reference state and the parameter sets as they were before the packet, its first field forgotten, so the packet decodes again from its start. A packet is read whole before any of it decodes, so one that is malformed (a frame and another picture, a third picture, a parameter set that does not parse) fails before it shows anything.
  • Of interlaced H.264 the decoder refuses, saying what: a sequence of fields on a device with output pictures apart from its reference pictures (the fields meet in the reference picture before the frame is copied out, the one way verified); a frame whose fields are a reference and none (no decoder pairs them, ffmpeg neither); a frame with a short-term and a long-term reference field, and a frame decoded as one picture of which one field alone is left a reference (a Vulkan Video reference picture is long-term or not, and a frame or the fields it was decoded as, as a whole); a picture whose slices' reference picture lists name more reference fields than the device decodes a picture from (NVIDIA: 16, each field of a frame decoded as two counting); and a gap in frame_num right after a field without its frame's other (ffmpeg conceals the gap with that field's frame, a skip slice would copy the frame before it). A picture with more reference fields than that names only the ones its slices' lists hold (8.2.4: the initial lists, field lists by alternating parity, cut to num_ref_idx_active and modified as the slice says), where a device given only those lays out the same lists.
  • A VP9 frame is the size its header says, whatever its references' (libvpx resizes a stream it cannot fit in its bitrate): the device scales the references as it predicts, each picture decoded at its own size into the pictures of the session its key frame made, so the frames' Size changes and the caller scales them to where it draws them. The session is made for the larger of the key frame and the frame size the container gives the track (demux.Track.Width and Height, libvpx's configured size, which it resizes down from), so frames that grow back to it keep their references. A frame larger than the session's pictures starts another session where it leaves nothing of the frames before it (a key frame, or an intra-only frame that refreshes every reference slot and resets every frame context); one that keeps reference pictures or frame contexts is refused (the reference pictures are layers of one image, as a device without VK_VIDEO_CAPABILITY_SEPARATE_REFERENCE_IMAGES_BIT_KHR (NVIDIA) needs, and the device keeps the frame contexts in the session, so neither carries over; a session for the device's largest pictures, 8192x8192 on NVIDIA, takes 955 MB where one of 1920x1080 takes 30), as is one naming a reference VP9 scales to no frame of its size (less than half or more than 16 times it).
  • A VP9 superframe or an AV1 temporal unit whose last frame fails (every frame held, say) keeps the frames before it that decoded: their reference slots, their probabilities (which a VP9 device keeps and cannot take back) and their hidden pictures stay. The same packet given again carries on from the frame that failed, the frames before it not decoded twice; a packet skipped instead leaves them decoded. A frame's header moves the parser's state (Stream.Update of internal/vp9 and of internal/av1) only once the frame has decoded, so a frame that fails reads the same again.
  • An H.265 picture moves the decoder's state (the picture order count the next pictures count from, the reference pictures it marks unused or long-term, whether the RASL pictures of the CRA picture decoding started at are dropped) only once its decode is submitted, so a packet that fails before that (every frame held, say) leaves the state as it was and decodes the same given again: a CRA picture decoding starts at after a seek still drops its RASL pictures.
  • An AV1 frame whose film grain pass fails, one decoded to be shown or one copied out to be shown again, goes back to the free frames, and the packet given again decodes or copies it once more.
  • A frame header that shows a picture shown before (AV1 and VP9 show_existing_frame) gets the picture copied out of its reference picture into a frame of its own again, with its film grain; a device with output pictures apart from its reference pictures copies nothing out of those, and refuses the stream there.
  • A VP9 intra frame decodes from frame context 0 and saves to it whatever frame_context_idx it codes, which the device is told as 0; the context coded is the one reset_frame_context 2 resets (the specification's setup_past_independence, as libvpx decodes it; ffmpeg decodes an intra-only frame from the context it codes instead, which agrees with libvpx only where context 0 is the default one). A Vulkan Video picture names one context, which a device resets, decodes from and saves to, so an intra-only frame that resets another one that frames saved to is decoded twice: first as a picture naming that context, resetting it and saving to none, into the DPB slot the frame then decodes into as it codes.
  • AV1 film grain comes out as dav1d synthesizes it, sample for sample. A device with output pictures apart from its reference pictures applies it; on one that decodes into its reference pictures alone (NVIDIA, Intel) the decoder synthesizes it: the host makes the grain templates, scaling functions and block offsets (internal/av1), and a compute pass of the graphics queue adds the noise to the frame's picture after its decode, ahead of any pass that draws it. Nothing waits for it, and Decoded covers it.
  • Every other depth and chroma format is put to the device: a stream it refuses fails with ErrNoVideoDecoder naming the profile, the samples and the answer of vkGetPhysicalDeviceVideoCapabilitiesKHR (VK_ERROR_VIDEO_PROFILE_FORMAT_NOT_SUPPORTED_KHR from NVIDIA for H.264 High 10, High 4:2:2 and High 4:4:4, 4:2:2 H.265, AV1 High and Professional and VP9 profiles 1 and 3; Intel's Mesa 26.2 refuses those too, and 12-bit and 4:4:4 H.265 and 12-bit VP9 besides). Those formats are verified on no device, so one that accepts the query is refused them too, saying so, rather than trusted with pictures nothing has checked. Monochrome streams have no picture format and are refused when parsed.
  • A stream in a format that is not decoded fails with ErrNoVideoDecoder, from NewVideoDecoder or the Decode that meets it, for every codec: the error says what the stream is and wraps what the parser read. A malformed stream fails with another error, so errors.Is(err, gpu.ErrNoVideoDecoder) tells the two apart.
  • A gap in H.264 frame_num that the SPS allows (gaps_in_frame_num_value_allowed_flag) infers the frames it leaves non-existing (8.2.5.2): each decodes as a skip slice copying the reference frame before it, so it holds a DPB slot and its place in the reference lists, and a stream predicting from it (frames lost) reads what ffmpeg conceals it with; ffmpeg deblocks such a stream a little differently, taking the copy for the frame it copies. In a sequence of fields or of macroblock-adaptive frames each inferred frame is a frame picture, both its fields references as 8.2.5.2 says, its picture order count the previous reference frame's plus 2 for both fields, as ffmpeg counts. ffmpeg marks only the field of the picture after the gap a reference in each, so where a field's lists reach past the inferred frame's first field the two disagree, and the decoder follows the standard. A gap the SPS does not allow is an error naming the frames missing.
  • internal/av1 reads the OBUs, sequence headers, frame headers (with the reference frame state they predict from) and tile groups; internal/vp9 reads superframe indexes and uncompressed headers (with the reference frame sizes, loop filter deltas, segmentation features and motion vector reuse they predict from, and which frame contexts frames saved to; the device reads the compressed header and keeps the probability contexts). Their tests check them against ffmpeg's trace_headers element for element. libvpx codes no intra-only frame, no frame shown twice and, through ffmpeg, no resized frame: the tests make the first two of the frames it does code (internal/vp9/vp9test), and gpu/testdata/vp9-resize.ivf is a stream vpxenc resized (gpu/testdata/README.md says how). x264 codes interlaced video as frames of field and frame macroblock pairs, never as field pictures: the tests make those of the pictures of progressive CAVLC streams at half the height, their slice headers rewritten (gpu/h264cut_test.go), which decode to pictures no encoder meant but the standard defines, and ffmpeg decodes as the reference. Field pictures coded with CABAC have no such source and no test in the tree; they, and what else real field encoders code (temporal direct prediction, weighted prediction, picture order count type 1, memory management in multi-reference streams), were checked once on the NVIDIA driver against 86 streams of the H.264 conformance suite (ITU-T H.264.1), 59 of them coding fields or macroblock-adaptive frames, 3984 field pictures in all: every one decodes as ffmpeg decodes it.
  • Where a picture goes follows the device's decode capabilities for the profile, not its vendor. One with output pictures apart from its reference pictures (VK_VIDEO_DECODE_CAPABILITY_DPB_AND_OUTPUT_DISTINCT_BIT_KHR) decodes into the frame directly. One that decodes into its reference pictures alone (..._DPB_AND_OUTPUT_COINCIDE_BIT_KHR only) has each picture copied out of its DPB slot into its frame: by the decode queue where that queue family copies images (NVIDIA), else by the graphics queue (Intel, whose video decode family has no transfer bit). There the reference pictures are shared by the two queue families (VK_SHARING_MODE_CONCURRENT) and the frames are the graphics queue's alone; the copy waits for the decode on the decoder's timeline semaphore, and every decode after it waits for the copy on a second one that the copy signals, since the copy moves its DPB layer through TRANSFER_SRC_OPTIMAL. The copy, film grain and the passes that draw the frame follow one another on the graphics queue, so a frame handed back is decoded into again once the passes that drew it are submitted, not finished; nothing waits on the CPU. Frames that are copies are the coded size, rounded up to whole chroma samples, rather than the DPB's size, so the sampler's edge clamping meets the coded picture and not memory no decode wrote.
  • Intel's driver (Mesa ANV) offers Vulkan Video decoding only with ANV_DEBUG=video-decode set (Mesa 26.2.5); without it DecodeCodecs is empty there. ANV never gives its AV1 decoder the segment IDs of a frame's primary reference frame: it leaves the segment ID read buffer unset and segment ID stream-in and stream-out off (genX_cmd_video.c, Mesa 26.2.5, 26.2.6 and main as of November 2026), so a frame that takes them (segmentation enabled with segmentation_update_map 0 or segmentation_temporal_update 1) decodes with whatever map the hardware holds, right only by chance. On ANV (VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA, whatever its version, since none sets the buffer) the Decode that meets such a frame fails with ErrNoVideoDecoder saying so, the frames before it decoded, rather than hand out a wrong frame: libaom's variance and cyclic refresh adaptive quantisation (-aq-mode 1 and 3) code them.
  • Decoding a frame allocates nothing once the decoder has made its frames.
  • A VideoDecoder belongs to its device's goroutine.

media/mux ​

mux writes timestamped H.264, H.265 and Opus samples into fragmented MP4 (NewMP4) and Matroska (NewMKV).

  • Video samples are Annex-B access units without B-frames. Audio samples are single Opus packets at 48 kHz.
  • A sample lasts until the next PTS on its track; the last repeats the previous duration. PTS must strictly increase within a track, on a clock shared by all tracks.
  • Whole fragments or clusters are written at once, so a truncated file plays up to the last one written.

media/demux ​

demux reads MP4/ISOBMFF (moov first or last, and fragmented), Matroska/WebM, Ogg, native FLAC and MPEG audio (MP3) in process. OpenFile gives the tracks (codec, frame size, sample rate, channels, codec config, delay and pre-roll) and the duration; ReadPacket returns packets in file order with PTS, duration and key flag, and Select skips the data of tracks nobody reads. Seek lands on a keyframe from stss or fragment flags in MP4 and from Cues in Matroska, scanning the clusters once when a file has no Cues. A track whose codec lys cannot decode reports it through Unsupported, an error naming the codec and the file. Every size is checked before it is allocated; malformed input wraps ErrMalformed, and any other format is ErrUnknownFormat.

Track.CodecDelay is what the container says to trim from the start: an MP4 edit list's media time (AAC's encoder priming), Matroska's CodecDelay or an Ogg Opus stream's pre-skip. Old Matroska AAC tracks that name their profile in the codec ID (A_AAC/MPEG4/LC and friends) and carry no CodecPrivate get an AudioSpecificConfig built from the profile, sample rate and channels. A FLAC track's Config is the body of its STREAMINFO block in every container.

  • Ogg: Vorbis, Opus and FLAC streams, one or several multiplexed; Theora, Speex and other streams are tracks whose codec is Unknown, named in CodecName. Every page's CRC is checked. A packet's PTS and duration come from the page's granule position and the packet's own length: an Opus packet's TOC, a FLAC frame's block size, a Vorbis packet's block size from the modes at the end of the setup header (found back from its end, as FFmpeg finds them). The first seek indexes the pages once and resumes after the last page that ends before the target. A chained file, a second stream beginning after the first one's data, fails with an error saying so.
  • FLAC: the frames of a native stream carry no length; each ends where the next frame's header begins and its CRC-16 sums to zero. A seek bisects the file for the frame. A stream whose STREAMINFO leaves its length unknown is timed by its last frame, and an ID3v1 tag at its end is skipped.
  • MPEG audio: ID3v2 tags before the frames and APEv2 and ID3v1 tags after them are skipped; Layer III is MP3, Layers I and II are Unknown, named in CodecName. A Xing, Info or VBRI header (after the side information as if the frame had no CRC, where LAME writes it) gives the frame count, and a LAME tag the encoder's delay and padding: the delay (with the 529 samples the synthesis adds) is the track's CodecDelay, and both come off its duration. A file without such a header is counted frame by frame on opening; the first seek indexes the frames, so it lands on the frame holding the target. mp3 decodes the frames.

File.Cover returns the picture a file embeds as its cover art, as stored: an MP4's covr item, a FLAC PICTURE block, an Ogg stream's METADATA_BLOCK_PICTURE comment, an ID3v2 APIC frame or a Matroska image attachment, the front cover where the file marks one. A Matroska file's front cover is the attachment named cover.jpg or cover.png, else its first image; of the other attachments only the headers are read.

media/flac ​

flac is a pure-Go FLAC decoder (RFC 9639). NewDecoder takes the STREAMINFO body that demux reports as a FLAC track's Config in a native, Ogg, Matroska or MP4 file; Decode turns one frame into interleaved signed 16-bit samples.

  • Every subframe type (constant, verbatim, fixed and LPC up to order 32), wasted bits, both Rice codings with escapes, every channel assignment, sample depths from 4 to 32 bits and up to eight channels in FLAC's (WAVE) order. Each frame's CRC-8 and CRC-16 are checked; a frame that breaks the format or the stream's parameters wraps ErrInvalidFrame.
  • Bit-exact: a decode at the stream's depth matches the encoder's MD5 in STREAMINFO. 16-bit output keeps a deeper sample's 16 most significant bits, as FFmpeg's conversion does, and scales a shallower one up.
  • Frames are independent, so Reset does nothing; no allocation per frame.
go
dec, err := flac.NewDecoder(track.Config)
if err != nil {
	return err
}
pcm, err := dec.Decode(nil, packet.Data)

media/mp3 ​

mp3 is a pure-Go MP3 decoder: MPEG-1, MPEG-2 and MPEG-2.5 Layer III. NewDecoder takes the sample rate and channel count that demux reports for an MP3 track of an MPEG audio, Matroska or MP4 file; Decode turns a packet of one or more whole frames into interleaved signed 16-bit samples, 1152 per channel a frame in MPEG-1 and 576 in MPEG-2 and 2.5.

  • Mono, stereo, dual channel and joint stereo (mid/side and intensity), long, short and mixed blocks, frames with a CRC (not checked) and the bit reservoir. Layers I and II are ErrUnsupported; a frame that breaks the format or the stream's rate or channel count wraps ErrInvalidFrame. Free-format streams do not demux.
  • Within an LSB of FFmpeg's decoder, about 100 dB SNR, on LAME's MPEG-1, 2 and 2.5 streams and on synthetic ones of mixed blocks and intensity stereo. Where FFmpeg departs from the standard, the decoder follows the standard: an MPEG-2 intensity position at its scale factor's largest value codes none, and a block overlaps the whole of the last one's second half whatever their types. Mixed blocks at 8 kHz split at 72 values, where their transform does; no other decoder was compared on them.
  • The output keeps the 529 samples the standard's synthesis delays it by, which the demuxer's CodecDelay and an MP4 edit list count; Matroska names no delay for MP3. After Reset a frame whose data begins in the frames before it decodes as silence, and the output joins the one decoding from the start gives once the bit reservoir and the overlap have filled again.
  • The Huffman trees, band widths and synthesis constants are minimp3's (public domain under CC0), copied by mp3/internal/genminimp3 from a pinned commit. Importing the package runs nothing: |q|^(4/3), the gains and the windows are computed by the first NewDecoder; no allocation per frame.
go
dec, err := mp3.NewDecoder(track.SampleRate, track.Channels)
if err != nil {
	return err
}
pcm, err := dec.Decode(nil, packet.Data)

media/opus ​

opus is a pure-Go Opus codec (RFC 6716). The encoder is CELT-only, fullband, 20 ms frames, from 48 kHz interleaved signed 16-bit PCM, one or two channels. Rate control is CBR or ConstrainedVBR (no packet exceeds twice the average). Tonality analysis is not implemented. AppendHead writes the stream's ID header.

The Decoder takes an OpusHead and decodes SILK, hybrid and CELT packets of every frame size (2.5 to 60 ms, up to 120 ms per packet) and bandwidth, with libopus's mode transitions and redundant CELT frames, within one LSB of libopus, applying the head's gain and libopus's soft clipping. Channel mapping families 0 (mono, stereo), 1 (Vorbis order, up to 8 channels: surround) and 255 decode; other families return ErrUnsupportedMapping. A frame of at most one byte (discontinuous transmission) is concealed as libopus conceals a lost frame: SILK's pitch and noise extrapolation with comfort noise bit-exactly, CELT's pitch or noise concealment within about 80 dB of libopus. Inband FEC (LBRR) is skipped; there is no call to conceal a whole lost packet. Like the Vorbis and AAC decoders it rounds each sample to 16 bits to nearest, halves to even, saturating, through the one conversion the three share.

Importing the package runs nothing: the MDCT, window and pulse codebook tables are built by the first NewEncoder or NewDecoder and shared by every one after it, so coding a frame does no lookup for them.

go
package main

import (
	"log"
	"os"
	"time"

	"github.com/stubbedev/lys/lib/media/mux"
	"github.com/stubbedev/lys/lib/media/opus"
)

func main() {
	const channels = 2
	enc, err := opus.NewEncoder(channels, 128000, opus.CBR)
	if err != nil {
		log.Fatal(err)
	}

	out, err := os.Create("silence.mp4")
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()
	m, err := mux.NewMP4(out, mux.Opus{Channels: channels, PreSkip: opus.PreSkip})
	if err != nil {
		log.Fatal(err)
	}

	pcm := make([]int16, opus.FrameSize*channels)
	frame := time.Second * opus.FrameSize / opus.SampleRate
	for i := range 50 {
		packet, err := enc.Encode(nil, pcm)
		if err != nil {
			log.Fatal(err)
		}
		sample := mux.Sample{Track: 0, PTS: time.Duration(i) * frame, Data: packet}
		if err := m.WriteSample(sample); err != nil {
			log.Fatal(err)
		}
	}
	if err := m.Close(); err != nil {
		log.Fatal(err)
	}
}

media/vorbis ​

vorbis is a pure-Go Ogg Vorbis I decoder. Decode reads the first logical Vorbis stream of an Ogg file and returns a Sound: sample rate, channel count and interleaved signed 16-bit samples. For packets from a container, NewDecoder takes the three headers and Decoder.Decode one packet at a time.

  • Full specification: floor types 0 and 1, residue types 0–2, coupling, any channel count. Every page CRC is checked.
  • Output is within one LSB of libvorbis.
  • Errors: ErrNotVorbis, ErrCorrupt, ErrTruncated. Codebook sizes are bounded, so hostile input cannot force unbounded allocation.
go
sound, err := vorbis.Decode(data)
if err != nil {
	return err
}
fmt.Println(sound.SampleRate, sound.Channels, sound.Frames())

media/aac ​

aac is a pure-Go MPEG-4 AAC-LC decoder (ISO/IEC 14496-3, audio object type 2). NewDecoder takes the AudioSpecificConfig that demux reports as the track's Config; Decode turns one raw data block into 1024 interleaved signed 16-bit samples per channel.

  • Channel configurations 1 to 7 (mono to 7.1), output in the configuration's order: centre first, then the front pair, the surround pairs and LFE.
  • Every LC tool: all window sequences and both window shapes, mid/side and intensity stereo, TNS, pulses and perceptual noise substitution, with the standard's correlated noise in mid/side bands. Within an LSB of ffmpeg's decoder (except the PNS noise itself); no allocation per frame.
  • ErrUnsupported names what a stream needs beyond LC: another object type (HE-AAC's SBR and PS, Main, LTP, ER and USAC), 960-sample frames, a program config element instead of a channel configuration, or a coupling channel element. Implicitly signalled SBR decodes as its LC core at the core rate. Dynamic range control data is ignored. Malformed input wraps ErrInvalid.
  • Importing the package runs nothing: the transform, window and codebook tables are built by the first NewDecoder and shared by every decoder after it.
  • An MP4 edit list's encoder priming is in the first packet's negative timestamp: drop that many samples from the start.
go
dec, err := aac.NewDecoder(track.Config)
if err != nil {
	return err
}
pcm, err := dec.Decode(nil, packet.Data)

audiomix ​

audiomix.Mixer sums sources of interleaved 16-bit PCM with clipping. New(sources, channels, backlog) creates it. Push queues a source's little-endian samples; Mix fills a frame from every source's oldest samples, padding missing ones with silence. A source more than backlog frames ahead is trimmed from its oldest samples.

v4l2 ​

v4l2 streams a V4L2 capture node in pure Go with mmap buffers.

  • Open(device, frame, maxFPS) requests YUYV, else MJPEG, near the frame's width and at least MinWidth (640).
  • Frames delivers *image.RGBA pictures letterboxed to the frame's aspect; Recycle returns one for reuse; Err says why the stream ended; Format names the negotiated format.
  • CaptureCard returns a node's card name if it captures video.

Released under the MIT License.