hwdec

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 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

hwdec

Status Go Reference

Hardware video decoding in pure Go.

Usage

d, err := hwdec.NewFrameDecoder(hwdec.Config{Codec: hwdec.H264, Width: 1920, Height: 1088})
if errors.Is(err, hwdec.ErrUnsupported) {
	// decode in software
}
defer d.Close()

err = d.Send(unit, pts)

s, pts, err := d.Receive()
err = s.Map(&img)
s.Release()

Send and Receive return ErrAgain when the other one has to be called first. After Flush, Receive returns the remaining pictures and then io.EOF.

Supported

  • V4L2 stateful decoders on 64-bit Linux: H.264, HEVC, VP8 and VP9, tested on the SpacemiT K1
  • VideoToolbox on macOS: H.264 and HEVC (Main and Main 10) with NewSliceDecoder

License

MIT, see LICENSE.

Documentation

Overview

Package hwdec decodes video with the hardware, through the interfaces of the operating system.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsupported is returned when no hardware decodes the stream.
	ErrUnsupported = errors.New("hwdec: not supported by the hardware")
	// ErrAgain is returned by Send when a picture has to be received first and by Receive when more input is needed.
	ErrAgain = errors.New("hwdec: try again")
	// ErrCorrupt is returned for a picture the hardware could not decode correctly, decoding can go on.
	ErrCorrupt = errors.New("hwdec: corrupt picture")
	// ErrHeld is returned by Receive when every picture buffer is held by the caller.
	ErrHeld = errors.New("hwdec: all surfaces are held")
	// ErrDevice is returned when the hardware failed, the decoder has to be closed.
	ErrDevice = errors.New("hwdec: device failed")
	// ErrClosed is returned when the decoder is closed or the surface released.
	ErrClosed = errors.New("hwdec: closed")
)

Functions

This section is empty.

Types

type AV1Params

type AV1Params struct {
	Profile, BitDepth, Layout int
	MatrixCoefficients        int
	FullRange                 bool
	OrderHintBits             int

	StillPicture, SB128, FilterIntra, IntraEdgeFilter, InterIntraCompound, MaskedCompound bool
	DualFilter, OrderHintEnabled, JntComp, CdefEnabled, FilmGrainPresent                  bool
	RestorationEnabled, RefFrameMVsEnabled                                                bool

	// MaxWidth and MaxHeight are the largest frame size of the sequence.
	MaxWidth, MaxHeight int
	// Width is the frame width after superres.
	Width, Height, SuperResDenom int
	// RefWidth and RefHeight are the sizes of the reference slots.
	RefWidth, RefHeight [8]int
	// RefreshFlags has a bit for each reference slot the frame replaces.
	RefreshFlags int

	FrameType, OrderHint, PrimaryRefFrame int
	RefIdx                                [7]int

	ShowFrame, ShowableFrame, ErrorResilient, DisableCdfUpdate, ScreenContentTools bool
	ForceIntegerMV, IntraBC, SuperRes, HighPrecisionMV, SwitchableMotionMode       bool
	UseRefFrameMVs, RefreshContext, UniformTileSpacing, WarpedMotion               bool
	ReferenceSelect, ReducedTxSet, SkipMode                                        bool
	InterpFilter, TxMode                                                           int

	TileCols, TileRows, ContextUpdateTileID int
	// TileWidths and TileHeights are in superblocks.
	TileWidths, TileHeights []int

	FilterLevel                           [2]int
	FilterLevelU, FilterLevelV, Sharpness int
	DeltaEnabled, DeltaUpdate             bool
	RefDeltas                             [8]int
	ModeDeltas                            [2]int

	BaseQIdx, DeltaQYDC, DeltaQUDC, DeltaQUAC, DeltaQVDC, DeltaQVAC int
	QM                                                              bool
	QMY, QMU, QMV                                                   int

	DeltaQPresent, DeltaLFPresent, DeltaLFMulti bool
	DeltaQResLog2, DeltaLFResLog2               int

	SegEnabled, SegUpdateMap, SegTemporal, SegUpdateData bool
	// SegFeatureMask has a bit for each enabled feature of a segment, SegFeatureData their values.
	SegFeatureMask [8]uint8
	SegFeatureData [8][8]int

	CdefDamping, CdefBits           int
	CdefYStrengths, CdefUVStrengths [8]int

	// RestorationType is the FrameRestorationType of each plane: none, Wiener, self-guided or switchable.
	RestorationType [3]int
	// RestorationSize is the log2 of the restoration unit size of luma and chroma.
	RestorationSize [2]int

	GlobalMotionType    [7]int
	GlobalMotion        [7][6]int32
	GlobalMotionInvalid [7]bool

	// Grain tells whether film grain is applied, with the parameters that follow as coded in the stream.
	Grain                                                            bool
	GrainSeed, GrainScalingShift, GrainARCoeffLag, GrainARCoeffShift int
	GrainScaleShift                                                  int
	GrainChromaFromLuma, GrainOverlap, GrainClipToRestrictedRange    bool
	GrainNumY, GrainNumCb, GrainNumCr                                int
	GrainY                                                           [14][2]uint8
	GrainCb, GrainCr                                                 [10][2]uint8
	GrainARY                                                         [24]int8
	GrainARCb, GrainARCr                                             [25]int8
	GrainCbMult, GrainCbLumaMult, GrainCbOffset                      int
	GrainCrMult, GrainCrLumaMult, GrainCrOffset                      int
}

AV1Params are the parameters of an AV1 frame.

type AV1Picture

type AV1Picture struct {
	Surface Surface
	// Display receives the picture with film grain, nil when none is applied.
	Display Surface
	// Refs are the surfaces of the eight reference slots, nil for an empty one.
	Refs   [8]Surface
	Data   []byte
	Tiles  []AV1Tile
	Params AV1Params
}

AV1Picture describes an AV1 frame to decode.

type AV1Tile

type AV1Tile struct {
	// Offset and Size locate the tile in the data of the frame.
	Offset, Size int
	Row, Col     int
}

AV1Tile is one tile of an AV1 frame.

type Codec

type Codec int

Codec is a compressed video format.

const (
	H264 Codec = iota + 1
	HEVC
	VP8
	VP9
	AV1
)

The codecs.

func (Codec) String

func (c Codec) String() string

type Config

type Config struct {
	Codec Codec
	// Width and Height are the coded size, a hint where the stream carries it.
	Width, Height int
	// Depth is the bit depth, 8 when zero.
	Depth int
	// Layout is the chroma layout, 420, 422 or 444, 420 when zero.
	Layout int
	// Device is the ID3D11Device to decode on, Windows only; when zero the decoder creates its own.
	Device uintptr
	// Surfaces is how many surfaces the caller holds at most, references included, a default when zero.
	Surfaces int
}

Config describes the stream to decode.

type DMABuf

type DMABuf struct {
	// Format is the DRM format code and Modifier the layout of the memory.
	Format   uint32
	Modifier uint64

	Width, Height int
	Planes        []DMABufPlane
}

DMABuf is a picture in memory the kernel can share with another device or process.

type DMABufPlane

type DMABufPlane struct {
	FD            int
	Offset, Pitch int
}

DMABufPlane is one plane of a DMABuf.

type DMABufSurface

type DMABufSurface interface {
	Surface
	// DMABuf waits for the picture and returns its memory, the same value each time. The descriptors stay valid while the decoder is open or any of its surfaces is held.
	DMABuf() (*DMABuf, error)
}

DMABufSurface is a surface whose memory can be shared.

type FrameDecoder

type FrameDecoder interface {
	// Send queues one access unit, Annex B with the parameter sets in band for H.264 and HEVC.
	Send(unit []byte, pts time.Duration) error
	// Receive is the next picture in display order and the time of its access unit, io.EOF after Flush and the last.
	Receive() (Surface, time.Duration, error)
	// Flush ends the stream.
	Flush() error
	// Reset drops everything queued, the next unit has to be a key frame.
	Reset() error
	// Close stops the decoder, surfaces still held stay valid.
	Close() error
}

FrameDecoder decodes whole access units. Its methods are not safe for concurrent use, those of its surfaces are.

func NewFrameDecoder

func NewFrameDecoder(c Config) (FrameDecoder, error)

NewFrameDecoder opens a decoder for c, ErrUnsupported without hardware for it.

type H264Picture

type H264Picture struct {
	Surface Surface
	Refs    []H264Ref

	// SPSData and PPSData are the parameter sets as in the stream.
	SPSData, PPSData []byte

	WidthMbs, HeightMbs int
	FrameNum            int
	POC                 [2]int

	Field, Bottom, Second, MBAFF, Reference bool

	ChromaFormatIDC       int
	MaxNumRefFrames       int
	GapsInFrameNumAllowed bool
	FrameMbsOnly          bool
	MbAdaptiveFrameField  bool
	Direct8x8Inference    bool
	MinLumaBiPred8x8      bool
	Log2MaxFrameNum       int
	PicOrderCntType       int
	Log2MaxPicOrderCntLsb int
	DeltaPicOrderZero     bool

	CABAC, WeightedPred, Transform8x8, ConstrainedIntra bool
	BottomFieldPicOrder, DeblockingControl, Redundant   bool

	WeightedBipredIDC   int
	PicInitQpMinus26    int
	PicInitQsMinus26    int
	ChromaQpOffset      [2]int
	BitDepth, BitDepthC int
	FullRange           bool

	// Scaling4x4 and Scaling8x8 are the scaling lists in zigzag order.
	Scaling4x4 [6][16]uint8
	Scaling8x8 [6][64]uint8
}

H264Picture holds the picture parameters of H.264.

type H264Ref

type H264Ref struct {
	// Surface is nil when the picture is missing.
	Surface Surface
	// FrameIdx is frame_num, or the long term index.
	FrameIdx int
	// POC is the order count of the top and bottom field.
	POC [2]int
	// Used tells which fields are references.
	Used [2]bool
	// Long is set for a long term reference.
	Long bool
	// Field is 0 or 1 for the top or bottom field of a frame, -1 for the frame.
	Field int
}

H264Ref is a reference picture.

type H264Slice

type H264Slice struct {
	// Data is the NAL unit as in the stream, and HeaderBits the size of its header without emulation prevention.
	Data       []byte
	HeaderBits int

	FirstMb       int
	Type          int
	DirectSpatial bool
	CabacInitIDC  int
	QpDelta       int

	DisableDeblocking                 int
	AlphaC0OffsetDiv2, BetaOffsetDiv2 int

	// NumRefIdx is the number of active entries of each list.
	NumRefIdx       [2]int
	List            [2][]H264Ref
	LumaLog2Denom   int
	ChromaLog2Denom int
	Weights         [2][]H264Weight
}

H264Slice holds the slice parameters of H.264.

type H264Weight

type H264Weight struct {
	LumaWeight, LumaOffset     int
	ChromaWeight, ChromaOffset [2]int
}

H264Weight are the prediction weights of one list entry.

type HEVCParams

type HEVCParams struct {
	Width, Height, POC  int
	ChromaFormatIDC     int
	BitDepth, BitDepthC int
	IRAP, IDR           bool
	FullRange           bool

	SeparatePlanes, PCM, ScalingList, TransformSkip, AMP, StrongIntraSmoothing bool
	SignDataHiding, ConstrainedIntra, CuQpDelta, WeightedPred, WeightedBipred  bool
	TransquantBypass, Tiles, EntropySync, LoopFilterSlices, LoopFilterTiles    bool
	PCMLoopFilterDisabled, ListsModification, LongTermRefs, TemporalMVP        bool
	CabacInit, OutputFlag, DependentSlices, SliceChromaQpOffsets, SAO          bool
	DeblockingOverride, DeblockingDisabled, SliceHeaderExtension               bool

	TransformSkipRotation, TransformSkipContext, ImplicitRdpcm, ExplicitRdpcm bool
	ExtendedPrecision, IntraSmoothingDisabled, HighPrecisionOffsets           bool
	PersistentRice, CabacBypassAlignment, CrossComponentPrediction            bool
	ChromaQpOffsetList                                                        bool

	MaxDecPicBuffering, MaxNumReorder        int
	MaxSubLayers                             int
	PCMBitDepth, PCMBitDepthC                int
	Log2MinCb, Log2Ctb, Log2MinTb, Log2MaxTb int
	Log2MinPCM, Log2MaxPCM                   int
	MaxTrHierarchyIntra, MaxTrHierarchyInter int
	InitQp, DiffCuQpDeltaDepth               int
	CbQpOffset, CrQpOffset                   int
	Log2ParallelMerge, Log2MaxPOCLsb         int
	NumShortTermSets, NumLongTermSPS         int
	NumRefIdxDefault                         [2]int
	BetaOffsetDiv2, TcOffsetDiv2             int
	NumExtraSliceHeaderBits                  int
	ShortTermSetBits, NumDeltaPocsRef        int

	Log2MaxTransformSkipSize, DiffCuChromaQpOffsetDepth int
	Log2SaoOffsetScaleLuma, Log2SaoOffsetScaleChroma    int
	ChromaQpOffsetListLen                               int
	CbQpOffsetList, CrQpOffsetList                      [6]int

	ColumnWidths, RowHeights []uint32

	// Scaling4x4 and the others are the scaling lists in raster order.
	Scaling4x4   [6][16]uint8
	Scaling8x8   [6][64]uint8
	Scaling16x16 [6][64]uint8
	Scaling32x32 [2][64]uint8
	ScalingDC16  [6]uint8
	ScalingDC32  [2]uint8
}

HEVCParams are the parameters of an HEVC picture.

type HEVCPicture

type HEVCPicture struct {
	Surface Surface
	Refs    []HEVCRef
	Params  HEVCParams

	// VPSData, SPSData and PPSData are the parameter sets as in the stream.
	VPSData, SPSData, PPSData []byte
}

HEVCPicture describes an HEVC picture to decode.

type HEVCRef

type HEVCRef struct {
	Surface Surface
	POC     int
	Long    bool
	// Before, After and LongCurr tell which part of the reference picture set of the current picture it is in.
	Before, After, LongCurr bool
}

HEVCRef is a reference picture.

type HEVCSlice

type HEVCSlice struct {
	// Data is the NAL unit as in the stream.
	Data   []byte
	Params HEVCSliceParams
	// List holds indices into the references of the picture, -1 for one that is missing.
	List [2][]int
}

HEVCSlice is one HEVC slice segment.

type HEVCSliceParams

type HEVCSliceParams struct {
	// HeaderSize is the size of the NAL unit before the slice data without emulation prevention, HeaderEPB the bytes removed from it.
	HeaderSize, HeaderEPB int

	Address, Type, ColorPlane int

	Dependent, SAOLuma, SAOChroma, MVDL1Zero, CabacInit, TemporalMVP bool
	DeblockingDisabled, CollocatedL0, LoopFilterAcross               bool

	CollocatedRefIdx             int
	NumRefIdx                    [2]int
	QpDelta                      int
	CbQpOffset, CrQpOffset       int
	BetaOffsetDiv2, TcOffsetDiv2 int
	MaxNumMergeCand              int
	EntryPoints                  int
	CuChromaQpOffset             bool

	Weighted                   bool
	LumaLog2, ChromaLog2       int
	LumaWeight, LumaOffset     [2][16]int16
	ChromaWeight, ChromaOffset [2][16][2]int16
}

HEVCSliceParams are the parameters of an HEVC slice segment.

type Image

type Image struct {
	Width, Height int
	Depth         int
	// Layout is the chroma layout, 420, 422 or 444.
	Layout int

	Y, Cb, Cr       []uint8
	Y16, Cb16, Cr16 []uint16

	StrideY, StrideC int
}

Image is a picture in memory, in Y, Cb and Cr for 8 bits or in the 16-bit planes for more.

func (*Image) SetAYUV

func (m *Image) SetAYUV(width, height int, src []byte, stride int) bool

SetAYUV copies a packed 8-bit 4:4:4 AYUV or XYUV picture into m, false when src is too short for it.

func (*Image) SetNV12

func (m *Image) SetNV12(width, height int, y, c []byte, strideY, strideC int) bool

SetNV12 copies an NV12 picture into m, false when the planes are too short for it.

func (*Image) SetP010

func (m *Image) SetP010(width, height, depth int, y, c []byte, strideY, strideC int) bool

SetP010 copies a P010 picture of the given depth into m, false when the planes are too short for it.

func (*Image) SetY210

func (m *Image) SetY210(width, height, depth int, src []byte, stride int) bool

SetY210 copies a packed 4:2:2 Y210 or Y212 picture of the given depth into m, false when src is too short for it.

func (*Image) SetY410

func (m *Image) SetY410(width, height int, src []byte, stride int) bool

SetY410 copies a packed 10-bit 4:4:4 Y410 picture into m, false when src is too short for it.

func (*Image) SetY412

func (m *Image) SetY412(width, height, depth int, src []byte, stride int) bool

SetY412 copies a packed 4:4:4 Y412 or Y416 picture of the given depth into m, false when src is too short for it.

func (*Image) SetYUY2

func (m *Image) SetYUY2(width, height int, src []byte, stride int) bool

SetYUY2 copies a packed 4:2:2 YUY2 picture into m, false when src is too short for it.

type NV12Surface

type NV12Surface interface {
	DMABufSurface
	// NV12 waits for the picture, converts it and returns the memory of the result, which follows the rules of DMABuf.
	NV12() (*DMABuf, error)
	// Scaled is like NV12 for the area x, y, w, h of the picture scaled to width by height.
	Scaled(x, y, w, h, width, height int) (*DMABuf, error)
}

NV12Surface is a surface whose picture the hardware can also convert to 8-bit NV12.

type SliceDecoder

type SliceDecoder interface {
	// NewSurface returns memory for a picture.
	NewSurface() (Surface, error)
	// BeginH264 starts a picture or a field.
	BeginH264(p *H264Picture) error
	// SliceH264 adds one slice.
	SliceH264(s *H264Slice) error
	// BeginHEVC starts a picture.
	BeginHEVC(p *HEVCPicture) error
	// SliceHEVC adds one slice segment.
	SliceHEVC(s *HEVCSlice) error
	// DecodeVP9 decodes a VP9 frame.
	DecodeVP9(p *VP9Picture) error
	// DecodeAV1 decodes an AV1 frame.
	DecodeAV1(p *AV1Picture) error
	// End completes the picture or the field.
	End() error
	// Reset forgets the references, the next picture starts the stream again.
	Reset() error
	// Close stops the decoder, surfaces still held are no longer valid.
	Close() error
}

SliceDecoder decodes slices parsed by the caller, who also manages the references.

func NewSliceDecoder

func NewSliceDecoder(c Config) (SliceDecoder, error)

NewSliceDecoder opens a decoder for c, ErrUnsupported without hardware for it.

type Surface

type Surface interface {
	// Size is the size of the decoded picture, which the hardware may have cropped.
	Size() (width, height int)
	// Map copies the picture to memory, reusing the planes of dst.
	Map(dst *Image) error
	// Release gives the picture back to the decoder.
	Release()
}

Surface is a decoded picture in the decoder's memory.

type VP9Params

type VP9Params struct {
	// RefWidth and RefHeight are the sizes of the reference slots.
	RefWidth, RefHeight [8]int

	// HeaderSize is the bytes of the uncompressed header and CompressedSize those of the compressed one.
	HeaderSize, CompressedSize int

	Profile, BitDepth          int
	SubsamplingX, SubsamplingY int
	Width, Height              int

	KeyFrame, ShowFrame, ErrorResilient, IntraOnly    bool
	RefreshContext, ParallelMode, AllowHP, UsePrevMVs bool
	ContextIdx, ResetContext, InterpFilter            int

	RefIdx   [3]int
	SignBias [4]bool

	FilterLevel, Sharpness int
	DeltaEnabled           bool
	RefDeltas              [4]int
	ModeDeltas             [2]int

	BaseQ, DeltaQYDC, DeltaQUVDC, DeltaQUVAC int

	SegEnabled, SegUpdateMap, SegTemporal, SegAbsDelta bool
	SegTreeProbs                                       [7]uint8
	SegPredProbs                                       [3]uint8
	SegFeatureMask                                     [8]uint8
	SegFeatureData                                     [8][4]int16

	// SegQuant are the luma and chroma DC and AC dequantizers of each segment, SegFilterLevel its loop filter levels by reference and mode.
	SegQuant       [8][2][2]int
	SegFilterLevel [8][4][2]int

	TileColsLog2, TileRowsLog2 int
}

VP9Params are the parameters of a VP9 frame.

type VP9Picture

type VP9Picture struct {
	Surface Surface
	// Refs are the surfaces of the eight reference slots, nil for an empty one.
	Refs [8]Surface
	// Data is the frame as in the stream.
	Data   []byte
	Params VP9Params
}

VP9Picture describes a VP9 frame to decode.

Directories

Path Synopsis
vaapi module

Jump to

Keyboard shortcuts

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