hidlcodec2

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: CC0-1.0 Imports: 9 Imported by: 0

Documentation

Overview

Package hidlcodec2 implements a HIDL Codec2 client for hardware video encoding via hwbinder. It connects to the software codec service (android.hardware.media.c2@1.2::IComponentStore/software) running in the media.swcodec process and talks the HIDL scatter-gather wire protocol.

This package follows the same patterns as gralloc/hidlalloc: open /dev/hwbinder, look up the service via hwservicemanager, build HwParcel requests, and parse raw reply bytes.

Index

Constants

View Source
const C2HandleGrallocExtraInts = 11

C2HandleGrallocExtraInts is the number of extra int32 values appended by C2HandleGralloc::WrapNativeHandle to the gralloc native_handle.

View Source
const C2HandleGrallocMagic = int32(0x007267C2)

C2HandleGrallocMagic is the magic value for C2HandleGralloc. Computed from the C++ multi-char literal '\xc2gr\x00': bytes LE: 0xC2, 'g'(0x67), 'r'(0x72), 0x00 -> uint32 0x007267C2.

View Source
const C2HandleIonMagic = int32(-1033277696) // 0xc2696f00

C2HandleIonMagic is the magic value for C2HandleIon / C2HandleBuf. Both Ion and DmaBuf allocators use this same magic to identify linear block handles.

Computed from the C++ multi-char literal '\xc2io\x00'.

Variables

This section is empty.

Functions

func BuildBitrateParam

func BuildBitrateParam(
	stream uint32,
	bitrate uint32,
) []byte

BuildBitrateParam builds a C2StreamBitrateInfo::output parameter.

The AVC encoder declares bitrate as an output-direction stream parameter (C2StreamBitrateInfo::output). The full index is: KIND_INFO | DIR_OUTPUT | IS_STREAM | (stream << 20) | 0x1000. Payload: uint32 bitrate.

func BuildC2Param

func BuildC2Param(
	index uint32,
	payload []byte,
) []byte

BuildC2Param constructs a single C2 parameter blob.

C2 param wire format:

[0:4] uint32 totalSize (= 8 + len(payload))
[4:8] uint32 paramIndex
[8:]  payload bytes

func BuildChannelCountParam

func BuildChannelCountParam(
	stream uint32,
	channelCount uint32,
) []byte

BuildChannelCountParam builds a C2StreamChannelCountInfo::input parameter.

The AAC encoder declares channel count as an input-direction stream parameter. The full index is: KIND_INFO | DIR_INPUT | IS_STREAM | (stream << 20) | 0x3001. Payload: uint32 channelCount.

func BuildPictureSizeParam

func BuildPictureSizeParam(
	stream uint32,
	width uint32,
	height uint32,
) []byte

BuildPictureSizeParam builds a C2StreamPictureSizeInfo::input parameter.

The AVC encoder declares picture size as an input-direction stream parameter (C2StreamPictureSizeInfo::input). The full index is: KIND_INFO | DIR_INPUT | IS_STREAM | (stream << 20) | 0x1800. Payload: uint32 width, uint32 height.

func BuildRangeInfoParam

func BuildRangeInfoParam(offset uint32, length uint32) []byte

BuildRangeInfoParam builds a C2Hal_RangeInfo parameter, which is required as the Block.Meta for linear blocks.

C2Hal_RangeInfo is C2GlobalParam<C2Info, C2Hal_Range, 0>. Index = KIND_INFO(0xC0000000) | DIR_GLOBAL(0x20000000) | 0 = 0xE0000000. Payload: uint32 offset, uint32 length.

func BuildSampleRateParam

func BuildSampleRateParam(
	stream uint32,
	sampleRate uint32,
) []byte

BuildSampleRateParam builds a C2StreamSampleRateInfo::input parameter.

The AAC encoder declares sample rate as an input-direction stream parameter. The full index is: KIND_INFO | DIR_INPUT | IS_STREAM | (stream << 20) | 0x3000. Payload: uint32 sampleRate.

func C2HandleGrallocInts

func C2HandleGrallocInts(
	width uint32,
	height uint32,
	format uint32,
	usage uint64,
	stride uint32,
) []int32

C2HandleGrallocInts builds the extra ints that C2HandleGralloc appends to a gralloc native_handle_t. The Codec2 framework recognizes handles with this trailing ExtraData as graphic blocks.

ExtraData layout (11 x int32):

[0] width
[1] height
[2] format (PixelFormat)
[3] usage_lo (low 32 bits of BufferUsage)
[4] usage_hi (high 32 bits of BufferUsage)
[5] stride
[6] generation
[7] igbp_id_lo
[8] igbp_id_hi
[9] igbp_slot
[10] magic (C2HandleGrallocMagic)

func C2HandleLinearInts

func C2HandleLinearInts(size uint64) []int32

C2HandleLinearInts builds the ints array for a C2HandleIon / C2HandleBuf native_handle_t. This handle format is recognized by the Codec2 framework as a linear block.

The native_handle_t should have numFds=1 (the buffer fd) and numInts=3 (sizeLo, sizeHi, magic).

func ConcatParams

func ConcatParams(params ...[]byte) []byte

ConcatParams concatenates multiple C2 param blobs into a single byte slice, with 8-byte alignment padding between params as required by the Codec2 wire format.

func RegisterListener

func RegisterListener(
	ctx context.Context,
	driver *kernelbinder.Driver,
	stub *ComponentListenerStub,
) uintptr

RegisterListener registers the listener stub with the hwbinder driver and returns the cookie that can be used to write a local binder reference in HIDL transactions.

func UnregisterListener

func UnregisterListener(
	ctx context.Context,
	driver *kernelbinder.Driver,
	cookie uintptr,
)

UnregisterListener removes the listener stub from the hwbinder driver.

Types

type BaseBlock

type BaseBlock struct {
	// Tag selects which union variant is active.
	// 0 = nativeBlock (handle), 1 = pooledBlock.
	Tag uint32

	// NativeBlock is used when Tag == 0.
	NativeBlockFds  []int32
	NativeBlockInts []int32
}

BaseBlock represents a memory block. For our use case we only support nativeBlock (a native_handle with FD + size).

type Block

type Block struct {
	Index     uint32
	Meta      []byte  // Params: concatenated C2Param blobs
	FenceFds  []int32 // Fence native_handle FDs (nil for null fence)
	FenceInts []int32 // Fence native_handle ints (nil for null fence)
}

Block references a BaseBlock within a WorkBundle.

type Buffer

type Buffer struct {
	Info   []byte // Params
	Blocks []Block
}

Buffer is a collection of Blocks with metadata.

type Component

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

Component is a HIDL client for IComponent on hwbinder.

func (*Component) Drain

func (c *Component) Drain(
	ctx context.Context,
	withEos bool,
) (_err error)

Drain calls IComponent::drain(withEos).

func (*Component) Flush

func (c *Component) Flush(
	ctx context.Context,
) (_err error)

Flush calls IComponent::flush() and returns the flushed WorkBundle. For simplicity, the returned WorkBundle is not fully parsed; we only check the status.

func (*Component) GetInterface

func (c *Component) GetInterface(
	ctx context.Context,
) (_ *ComponentInterface, _err error)

GetInterface calls IComponent::getInterface() and returns the IComponentInterface handle.

func (*Component) Handle

func (c *Component) Handle() uint32

Handle returns the binder handle for this component.

func (*Component) Queue

func (c *Component) Queue(
	ctx context.Context,
	wb *WorkBundle,
) (_err error)

Queue calls IComponent::queue() with the given WorkBundle. The workBundle is serialized as a HIDL WorkBundle struct.

func (*Component) Release

func (c *Component) Release(
	ctx context.Context,
) (_err error)

Release calls IComponent::release().

func (*Component) Reset

func (c *Component) Reset(
	ctx context.Context,
) (_err error)

Reset calls IComponent::reset().

func (*Component) Start

func (c *Component) Start(
	ctx context.Context,
) (_err error)

Start calls IComponent::start().

func (*Component) Stop

func (c *Component) Stop(
	ctx context.Context,
) (_err error)

Stop calls IComponent::stop().

type ComponentInterface

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

ComponentInterface is a HIDL client for IComponentInterface.

func (*ComponentInterface) GetConfigurable

func (ci *ComponentInterface) GetConfigurable(
	ctx context.Context,
) (_ *Configurable, _err error)

GetConfigurable calls IComponentInterface::getConfigurable() and returns a Configurable client.

type ComponentListenerStub

type ComponentListenerStub struct {
	// OnWorkDone is called when the component finishes processing work.
	// The raw reply data is passed for callers who want to inspect it.
	// May be nil if the caller does not need callbacks.
	OnWorkDone func(data []byte)
}

ComponentListenerStub is a minimal HIDL binder stub for IComponentListener. It receives oneway callbacks from the Codec2 component (onWorkDone, onTripped, onError, etc.) and silently acknowledges them.

The stub implements binder.TransactionReceiver so it can be registered with the kernelbinder.Driver to receive incoming BR_TRANSACTION events.

func (*ComponentListenerStub) Descriptor

func (s *ComponentListenerStub) Descriptor() string

Descriptor returns the HIDL interface descriptor.

func (*ComponentListenerStub) OnTransaction

func (s *ComponentListenerStub) OnTransaction(
	ctx context.Context,
	code binder.TransactionCode,
	data *parcel.Parcel,
) (*parcel.Parcel, error)

OnTransaction handles incoming HIDL transactions from the component. IComponentListener methods are all oneway, so no reply is expected.

HIDL transaction codes for IComponentListener 1.0:

1: onWorkDone(WorkBundle)
2: onTripped(vec<SettingResult>)
3: onError(Status, uint32)
4: onFramesRendered(vec<RenderedFrame>)
5: onInputBuffersReleased(vec<InputBuffer>)

type ComponentStore

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

ComponentStore is a HIDL client for IComponentStore on hwbinder.

func GetComponentStore

func GetComponentStore(
	ctx context.Context,
	transport binder.Transport,
) (_ *ComponentStore, _err error)

GetComponentStore looks up the Codec2 IComponentStore service via hwservicemanager and returns a client. It tries @1.2 first, then falls back to @1.0.

func (*ComponentStore) CreateComponent

func (s *ComponentStore) CreateComponent(
	ctx context.Context,
	name string,
	listenerCookie uintptr,
) (_ *Component, _err error)

CreateComponent calls IComponentStore::createComponent() to create a component by name.

listenerCookie must be a non-zero cookie returned by RegisterListener (which registers a ComponentListenerStub with the hwbinder driver). The cookie is used to write a BINDER_TYPE_BINDER flat_binder_object that the Codec2 service will use for callbacks.

For the 1.2 store, it calls createComponent_1_2; for 1.0, the base createComponent. The pool manager is always null (no BufferPool).

func (*ComponentStore) Handle

func (s *ComponentStore) Handle() uint32

Handle returns the binder handle for this store.

func (*ComponentStore) ListComponents

func (s *ComponentStore) ListComponents(
	ctx context.Context,
) (_ []ComponentTraits, _err error)

ListComponents calls IComponentStore::listComponents() and returns the available codec traits.

type ComponentTraits

type ComponentTraits struct {
	Name      string
	Domain    Domain
	Kind      Kind
	Rank      uint32
	MediaType string
	Aliases   []string
}

ComponentTraits describes a single Codec2 component.

type Configurable

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

Configurable is a HIDL client for IConfigurable.

func (*Configurable) Config

func (cfg *Configurable) Config(
	ctx context.Context,
	inParams []byte,
	mayBlock bool,
) (_ Status, _ []byte, _err error)

Config calls IConfigurable::config() with the given C2 parameter blob.

inParams is the concatenation of C2Param structs (each prefixed with uint32 size + uint32 index).

Returns the C2 status and the output params blob.

func (*Configurable) GetId

func (cfg *Configurable) GetId(
	ctx context.Context,
) (_ uint32, _err error)

GetId calls IConfigurable::getId().

func (*Configurable) GetName

func (cfg *Configurable) GetName(
	ctx context.Context,
) (_ string, _err error)

GetName calls IConfigurable::getName() and returns the component name.

type Domain

type Domain uint32

Domain classifies the media type of a component.

const (
	DomainOther Domain = 0
	DomainVideo Domain = 1
	DomainAudio Domain = 2
	DomainImage Domain = 3
)

type FrameData

type FrameData struct {
	Flags        FrameDataFlags
	Ordinal      WorkOrdinal
	Buffers      []Buffer
	ConfigUpdate []byte // Params

}

FrameData carries input or output frame data.

type FrameDataFlags

type FrameDataFlags uint32

FrameDataFlags are bitfield flags for FrameData.

const (
	FrameDataDropFrame    FrameDataFlags = 1 << 0
	FrameDataEndOfStream  FrameDataFlags = 1 << 1
	FrameDataDiscardFrame FrameDataFlags = 1 << 2
	FrameDataIncomplete   FrameDataFlags = 1 << 3
	FrameDataCodecConfig  FrameDataFlags = 1 << 31
)

type Kind

type Kind uint32

Kind classifies whether a component is a decoder or encoder.

const (
	KindOther   Kind = 0
	KindDecoder Kind = 1
	KindEncoder Kind = 2
)

type Status

type Status int32

Status is the Codec2 status code.

The HIDL types.hal defines Status with negative values, but the actual HIDL implementation (Configurable.cpp) casts raw c2_status_t values (positive POSIX errno) directly into the wire format:

_hidl_cb((Status)c2res, failures, outParams);

So on the wire we see positive errno values (EINVAL=22, ENXIO=6, etc.), not the negative HIDL-spec values. We define both sets for correct matching.

const (
	StatusOK        Status = 0
	StatusBadState  Status = 1   // EPERM
	StatusNotFound  Status = 2   // ENOENT
	StatusCanceled  Status = 4   // EINTR
	StatusBadIndex  Status = 6   // ENXIO
	StatusBlocking  Status = 11  // EAGAIN/EWOULDBLOCK
	StatusNoMemory  Status = 12  // ENOMEM
	StatusRefused   Status = 13  // EACCES
	StatusCorrupted Status = 14  // EFAULT
	StatusDuplicate Status = 17  // EEXIST
	StatusNoInit    Status = 19  // ENODEV
	StatusBadValue  Status = 22  // EINVAL
	StatusOmitted   Status = 38  // ENOSYS
	StatusCannotDo  Status = 95  // ENOTSUP (EOPNOTSUPP on some systems)
	StatusTimedOut  Status = 110 // ETIMEDOUT
)

Positive-errno values as seen on the HIDL wire (c2_status_t raw values). The AOSP HIDL server implementations use static_cast<Status>(c2_status_t), so the wire carries raw POSIX errno values.

const (
	StatusHIDLCorrupted Status = -2147483648 // types.hal CORRUPTED
)

HIDL types.hal negative Status values. Some internal error paths in the HIDL transport may return these instead of the positive-errno values above (e.g., when the framework itself detects corruption before delegating to the C2 component).

func (Status) Err

func (s Status) Err() error

Err returns nil if status is OK, otherwise an error.

func (Status) String

func (s Status) String() string

String returns a human-readable name for the status code.

type Work

type Work struct {
	ChainInfo         []byte // Params
	Input             FrameData
	Worklets          []Worklet
	WorkletsProcessed uint32
	Result            Status
}

Work represents a single work item.

type WorkBundle

type WorkBundle struct {
	Works      []Work
	BaseBlocks []BaseBlock
}

WorkBundle bundles works and base blocks for IPC efficiency.

func (*WorkBundle) WriteTo

func (wb *WorkBundle) WriteTo(hp *hwparcel.HwParcel)

WriteTo serializes the WorkBundle into the HwParcel using HIDL scatter-gather format with proper parent-child buffer relationships.

type WorkOrdinal

type WorkOrdinal struct {
	TimestampUs   uint64
	FrameIndex    uint64
	CustomOrdinal uint64
}

WorkOrdinal describes the ordering of a frame.

type Worklet

type Worklet struct {
	ComponentId uint32
	Tunings     []byte // Params

}

Worklet describes processing for one output frame.

Jump to

Keyboard shortcuts

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