diff --git a/codec_parameters.go b/codec_parameters.go index f77b20a..604061c 100644 --- a/codec_parameters.go +++ b/codec_parameters.go @@ -3,6 +3,10 @@ package astiav //#cgo pkg-config: libavcodec //#include import "C" +import ( + "fmt" + "unsafe" +) // https://github.com/FFmpeg/FFmpeg/blob/n5.0/libavcodec/codec_par.h#L52 type CodecParameters struct { @@ -141,6 +145,37 @@ func (cp *CodecParameters) SetSampleAspectRatio(r Rational) { cp.c.sample_aspect_ratio = r.c } +func (cp *CodecParameters) ExtraData() []byte { + return bytesFromC(func(size *C.size_t) *C.uint8_t { + if cp.c.extradata == nil { + *size = C.size_t(0) + return nil + } + *size = C.size_t(cp.c.extradata_size) + return cp.c.extradata + }) +} + +func (cp *CodecParameters) SetExtraData(extraData []byte) error { + if len(extraData) == 0 { + return nil + } + + if cp.c.extradata != nil { + C.av_freep(unsafe.Pointer(&cp.c.extradata)) + cp.c.extradata_size = 0 + } + + extradataSize := len(extraData) + if cp.c.extradata = (*C.uint8_t)(C.av_mallocz(C.size_t(extradataSize + C.AV_INPUT_BUFFER_PADDING_SIZE))); cp.c.extradata == nil { + return fmt.Errorf("astiav: allocation is nil") + } + + C.memcpy(unsafe.Pointer(cp.c.extradata), unsafe.Pointer(&extraData[0]), C.size_t(extradataSize)) + cp.c.extradata_size = C.int(extradataSize) + return nil +} + func (cp *CodecParameters) SampleFormat() SampleFormat { return SampleFormat(cp.c.format) } diff --git a/codec_parameters_test.go b/codec_parameters_test.go index 711b14e..c3c3da1 100644 --- a/codec_parameters_test.go +++ b/codec_parameters_test.go @@ -95,4 +95,8 @@ func TestCodecParameters(t *testing.T) { require.Equal(t, 4, cp6.SampleRate()) cp6.SetWidth(2) require.Equal(t, 2, cp6.Width()) + + extraBytes := []byte{0, 0, 0, 1} + require.NoError(t, cp6.SetExtraData(extraBytes)) + require.Equal(t, extraBytes, cp6.ExtraData()) }