asticode / go-astiav

Golang ffmpeg and libav C bindings
MIT License
393 stars 45 forks source link

Enhance Codec Iteration and Checking of HardwareConfigMethodFlags #40

Closed Cacsjep closed 9 months ago

Cacsjep commented 9 months ago

Hey

During intergration steps of hw decoding I see that some thing would be very handy.

1. Hardware Configuration Flag Check: A method HasHardwareConfigMethodFlag in the Codec struct allows checking if a codec supports a specific hardware configuration method. This is particularly useful for identifying if a codec is hardware accelerated.

Implementation snippet:

func (c *Codec) HasHardwareConfigMethodFlag(chcmf CodecHardwareConfigMethodFlag) bool {
    var i C.int
    for {
        config := C.avcodec_get_hw_config(c.c, i)
        if config == nil {
            break
        }
        if (CodecHardwareConfig{c: config}.MethodFlags().Has(chcmf)) {
            return true
        }
        i++
    }
    return false
}

2. Codec Iteration Enhancement: A new function IterateCodecs simplifies the process of iterating over available codecs. This function takes a CodecProcessor and applies it to each codec, facilitating custom processing logic per codec.

Implementation snippet:

func IterateCodecs(processor CodecProcessor) {
    var opq *C.void = nil
    for {
        c := C.av_codec_iterate((*unsafe.Pointer)(unsafe.Pointer(&opq)))
        if c == nil {
            break
        }
        codec := newCodecFromC(c)
        processor(codec)
    }
}

3. Codec Identification: Added a method ID to the Codec struct to retrieve the codec's ID, aiding in the identification and filtering of codecs.

func (c *Codec) ID() CodecID {
    return CodecID(c.c.id)
}

Use Case These enhancements allow for efficient identification and selection of codecs based on capabilities and specific codec IDs. This is particularly useful in scenarios where an application needs to support multiple codecs across different operating systems and offers the user the ability to switch between different decoders.

A practical example of using these enhancements is shown below:

var decoders []*astiav.Codec
processor := func(c *astiav.Codec) {
    if c.IsDecoder() && c.HasHardwareConfigMethodFlag(astiav.CodecHardwareConfigMethodFlagHwDeviceCtx) && c.ID() == astiav.CodecIDMjpeg {
        decoders = append(decoders, c)
    }
}
astiav.IterateCodecs(processor)

Br christoph

Cacsjep commented 9 months ago

Done =)

asticode commented 9 months ago

Perfect, I'll merge the PR and make minor adjustments 👍