avcpp 3.2.1
Wrapper for the FFmpeg that simplify usage from C++ projects.
Loading...
Searching...
No Matches
av::VideoEncoderContext Class Reference

Encodes video frames into packets. More...

#include <codeccontext.h>

Inheritance diagram for av::VideoEncoderContext:

Public Types

using Parent = VideoCodecContext<VideoEncoderContext, Direction::Encoding>
 /// The base class this context derives from.
Public Types inherited from av::VideoCodecContext< VideoEncoderContext, Direction::Encoding >
using Parent
 The base class this context derives from.

Public Member Functions

 VideoEncoderContext ()=default
 Create an empty encoder; set a codec and open() it later.
 VideoEncoderContext (VideoEncoderContext &&other)
 Move the encoder.
VideoEncoderContext & operator= (VideoEncoderContext &&other)
 Move assignment.
Packet encode (OptionalErrorCode ec=throws())
 encodeVideo - Flush encoder
Packet encode (const VideoFrame &inFrame, OptionalErrorCode ec=throws())
 encodeVideo - encode video frame
bool send (const VideoFrame &frame, OptionalErrorCode ec=throws())
 Sends a frame to the encoder.
Packet receive (OptionalErrorCode ec=throws())
 Receives one encoded packet.
void setHwDeviceContext (const hw::DeviceContext &device, OptionalErrorCode ec=throws())
 Sets AVCodecContext::hw_device_ctx before open().
void clearHwDeviceContext () noexcept
 Removes the hardware device context.
void setHwFramesContext (const hw::FramesContext &frames, OptionalErrorCode ec=throws())
 Sets AVCodecContext::hw_frames_ctx before open().
void clearHwFramesContext () noexcept
 Removes the hardware frames context.
hw::DeviceContext hwDeviceContext () const noexcept
 Device configured for this encoder.
hw::FramesContext hwFramesContext () const noexcept
 Frames context configured for this encoder.
void configureHwEncoding (const hw::DeviceContext &device, hw::EncodingMode mode=hw::EncodingMode::Auto, PixelFormat swFormat=AV_PIX_FMT_NONE, OptionalErrorCode ec=throws())
 Configures hardware encoding for the given device.
void configureHwEncoding (const hw::FramesContext &frames, OptionalErrorCode ec=throws())
 Uses an existing frames context (zero-copy).
hw::EncodingMode hwEncodingMode () const noexcept
 How the encoder receives hardware frames.
bool isHwEncoding () const noexcept
 Whether hardware encoding is configured.
void setHwAutoUpload (bool enabled) noexcept
 Upload software frames automatically before encoding.
bool isHwAutoUpload () const noexcept
 Whether software frames are uploaded automatically.
Public Member Functions inherited from av::VideoCodecContext< VideoEncoderContext, Direction::Encoding >
int width () const
 Frame width stored in the context.
int height () const
 Frame height stored in the context.
int codedWidth () const
 Width as coded by the bitstream, before any cropping.
int codedHeight () const
 Height as coded by the bitstream, before any cropping.
PixelFormat pixelFormat () const
 Pixel format the codec works with.
int32_t globalQuality () const
 Global quality value used by constant-quality encoders.
int32_t gopSize () const
 Distance between key frames.
int bitRateTolerance () const
 How far the encoder may deviate from the target bit rate.
int maxBFrames () const
 Maximum number of B-frames the encoder may use.
Rational sampleAspectRatio () const
 Pixel aspect ratio of the frames.
void setWidth (int w)
 Set the frame width.
void setHeight (int h)
 Set the frame height.
void setCodedWidth (int w)
 Set the coded width independently of the display width.
void setCodedHeight (int h)
 Set the coded height independently of the display height.
void setPixelFormat (PixelFormat pixelFormat)
 Set the pixel format.
void setGlobalQuality (int32_t quality)
 Set the global quality for constant-quality encoders.
void setGopSize (int32_t size)
 Set the distance between key frames.
void setBitRateTolerance (int bitRateTolerance)
 Set how far the encoder may deviate from the target bit rate.
void setMaxBFrames (int maxBFrames)
 Limit the number of B-frames.
void setSampleAspectRatio (const Rational &sampleAspectRatio)
 Set the pixel aspect ratio.
Public Member Functions inherited from av::CodecContextBase< Clazz, _direction, _type >
 CodecContextBase ()
 Create an empty context of this direction and media type.
 CodecContextBase (const class Stream &st, const class Codec &codec=Codec())
 Create a context attached to a stream.
 CodecContextBase (const Codec &codec)
 Create a context for a codec, without a stream.
 CodecContextBase (CodecContextBase &&other)
 Move the context.
void setCodec (const Codec &codec, OptionalErrorCode ec=throws())
 Choose the codec without resetting its defaults.
void setCodec (const Codec &codec, bool resetDefaults, OptionalErrorCode ec=throws())
 Choose the codec.
AVMediaType codecType () const noexcept
 The media type of this context.
bool flush (OptionalErrorCode ec=throws())
 Puts the codec into draining mode.
void _log (int level, const char *fmt) const
 Log through the FFmpeg log system, using this wrapper as the context.
void _log (int level, const char *fmt, const Args &... args) const
 Log through the FFmpeg log system with arguments.
Public Member Functions inherited from av::CodecContext2
void open (OptionalErrorCode ec=throws())
 Open the codec with the parameters set so far.
void open (const Codec &codec, OptionalErrorCode ec=throws())
 Open the codec, choosing it explicitly.
void open (class Dictionary &options, OptionalErrorCode ec=throws())
 Open the codec with options.
void open (class Dictionary &&options, OptionalErrorCode ec=throws())
 Open the codec with options, taking ownership of the dictionary.
void open (class Dictionary &options, const Codec &codec, OptionalErrorCode ec=throws())
 Open an explicitly chosen codec with options.
void open (class Dictionary &&options, const Codec &codec, OptionalErrorCode ec=throws())
 Open an explicitly chosen codec with options, moving the dictionary.
void close (OptionalErrorCode ec=throws())
 Close the codec context.
bool isOpened () const noexcept
 Whether the codec has been opened.
bool isValid () const noexcept
 Whether the context owns an FFmpeg codec context.
Rational timeBase () const noexcept
 Time base of the codec.
void setTimeBase (const Rational &value) noexcept
 Set the time base.
Rational frameRate () const noexcept
 Frame rate advertised by the codec.
void setFrameRate (const Rational &value) noexcept
 Set the frame rate.
bool isEof () const noexcept
 Returns true if the codec has been flushed and all output is drained.
void flushBuffers () noexcept
 Resets the codec internal state and the end-of-stream flag.
const Stream & stream () const noexcept
 The stream this context is attached to.
Codec codec () const noexcept
 The codec in use.
void setOption (const std::string &key, const std::string &val, OptionalErrorCode ec=throws())
 Set a private codec option.
void setOption (const std::string &key, const std::string &val, int flags, OptionalErrorCode ec=throws())
 Set a private codec option with AVDictionary flags.
int frameSize () const noexcept
 Number of samples per frame the codec works with.
int64_t frameNumber () const noexcept
 Counter of frames passed through the context.
bool isRefCountedFrames () const noexcept
 Whether the codec hands out reference-counted frames.
void setRefCountedFrames (bool refcounted) const noexcept
 Ask the codec for reference-counted frames.
int strict () const noexcept
 Current strictness level of the codec.
void setStrict (int strict) noexcept
 Set the strictness level.
int64_t bitRate () const noexcept
 Target bit rate.
std::pair< int64_t, int64_t > bitRateRange () const noexcept
 Allowed bit rate range.
void setBitRate (int64_t bitRate) noexcept
 Set the target bit rate.
void setBitRateRange (const std::pair< int64_t, int64_t > &bitRateRange) noexcept
 Set the allowed bit rate range.
template<typename T>
std::pair< int, const std::error_category * > decodeCommon (T &outFrame, const class Packet &inPacket, size_t offset, int &frameFinished, int(*decodeProc)(AVCodecContext *, AVFrame *, int *, const AVPacket *))
 Decode one packet into a typed frame.
template<typename T>
std::pair< int, const std::error_category * > encodeCommon (class Packet &outPacket, const T &inFrame, int &gotPacket, int(*encodeProc)(AVCodecContext *, AVPacket *, const AVFrame *, int *))
 Encode one typed frame into a packet.
bool send (const Packet &packet, OptionalErrorCode ec=throws())
 Submit a packet to a decoder.
Packet receive (OptionalErrorCode ec=throws())
 Read one decoded packet from an encoder.
void _log (int level, const char *fmt) const
 Log through the FFmpeg log system, using this wrapper as the context.
void _log (int level, const char *fmt, const Args &... args) const
 Log through the FFmpeg log system with arguments.
void copyContextFrom (const CodecContext2 &other, OptionalErrorCode ec=throws())
 Copy codec context from codec context associated with given stream or other codec context.
void setFlags (int flags) noexcept
 Access to CODEC_FLAG_* flags.
void addFlags (int flags) noexcept
 Add AV_CODEC_FLAG_* flags.
void clearFlags (int flags) noexcept
 Remove AV_CODEC_FLAG_* flags.
int flags () noexcept
 Current AV_CODEC_FLAG_* mask.
bool isFlags (int flags) noexcept
 Whether all given flags are set.
void setFlags2 (int flags) noexcept
 Access to CODEC_FLAG2_* flags.
void addFlags2 (int flags) noexcept
 Add AV_CODEC_FLAG2_* flags.
void clearFlags2 (int flags) noexcept
 Remove AV_CODEC_FLAG2_* flags.
int flags2 () noexcept
 Current AV_CODEC_FLAG2_* mask.
bool isFlags2 (int flags) noexcept
 Whether all given flags are set.
Public Member Functions inherited from FFWrapperPtr< AVCodecContext >
 FFWrapperPtr ()=default
 Create an empty wrapper; isNull() is true.
 FFWrapperPtr (AVCodecContext *raw)
 Wrap an existing object.
const AVCodecContext * raw () const
 Read access to the wrapped object.
AVCodecContext * raw ()
 Write access to the wrapped object.
void reset (AVCodecContext *raw=nullptr)
 Replace the stored pointer.
bool isNull () const
 Whether the wrapper is empty.
void _log (int level, const char *fmt) const
 Log through the FFmpeg log system, using this wrapper as the context.
void _log (int level, const char *fmt, const Args &... args) const
 Log through the FFmpeg log system with arguments.

Additional Inherited Members

Protected Types inherited from av::CodecContext2
using BaseWrapper = FFWrapperPtr<AVCodecContext>
 /// The reference-counting wrapper this context builds on.
Protected Member Functions inherited from av::VideoCodecContext< VideoEncoderContext, Direction::Encoding >
VideoEncoderContext & moveOperator (VideoEncoderContext &&rhs)
 Move-assign the derived object and return it.
Protected Member Functions inherited from av::CodecContextBase< Clazz, _direction, _type >
Clazz & moveOperator (Clazz &&rhs)
 Move-assign the derived object and return it.
void setCodec (const class Codec &codec, bool resetDefaults, Direction direction, AVMediaType type, OptionalErrorCode ec=throws())
 Attach a codec and validate it against the direction and media type.
Protected Member Functions inherited from av::CodecContext2
void swap (CodecContext2 &other)
 Exchange the state of two contexts.
 CodecContext2 (const class Stream &st, const class Codec &codec, Direction direction, AVMediaType type)
 Create a context attached to a stream.
 CodecContext2 (const class Codec &codec, Direction direction, AVMediaType type)
 Create a context for a codec without a stream.
void setCodec (const class Codec &codec, bool resetDefaults, Direction direction, AVMediaType type, OptionalErrorCode ec=throws())
 Attach a codec and validate it against the direction and media type.
AVMediaType codecType (AVMediaType contextType) const noexcept
 Map a context media type to the effective media type.
bool isValidForEncode (Direction direction, AVMediaType type) const noexcept
 Whether the configured codec can encode the given media type.
bool checkCodec (const Codec &codec, Direction direction, AVMediaType type, OptionalErrorCode ec)
 Validate a codec against a direction and media type, reporting the reason.
void open (const Codec &codec, AVDictionary **options, OptionalErrorCode ec)
 Open the codec with raw FFmpeg options.
std::pair< int, const std::error_category * > decodeCommon (AVFrame *outFrame, const class Packet &inPacket, size_t offset, int &frameFinished, int(*decodeProc)(AVCodecContext *, AVFrame *, int *, const AVPacket *)) noexcept
 Decode one packet into an FFmpeg frame.
std::pair< int, const std::error_category * > encodeCommon (class Packet &outPacket, const AVFrame *inFrame, int &gotPacket, int(*encodeProc)(AVCodecContext *, AVPacket *, const AVFrame *, int *)) noexcept
 Encode one typed frame into a packet.
std::error_code sendCommon (const class Packet &pkt)
 Submit a packet to a decoder.
std::error_code receiveCommon (AVFrame *frame)
 Read one frame from a decode context.
template<typename T>
std::error_code receiveCommon (T &frame)
 Read one typed output object from a decode context.
std::error_code sendCommon (const AVFrame *frame)
 Submit a frame to an encoder.
std::error_code receiveCommon (class Packet &pkt)
 Read one packet from an encode context.
template<typename T>
std::error_code sendCommon (const T &frame)
 Submit a typed frame to an encoder.
Protected Member Functions inherited from av::noncopyable
 noncopyable (const noncopyable &)=delete
void operator= (const noncopyable &)=delete
Protected Attributes inherited from av::CodecContext2
hw::DeviceContext m_hwDevice
 Device attached by setHwDeviceContext() or configureHwEncoding().
hw::FramesContext m_hwFrames
 Pool attached by setHwFramesContext() or configureHwEncoding().
bool m_hwTransferToSystem = false
 Whether decoded hardware frames are copied to system memory automatically.
bool m_hwAutoUpload = true
 Whether software frames are uploaded into the pool before encoding.
hw::EncodingMode m_hwEncodingMode = hw::EncodingMode::Auto
 How the encoder receives hardware frames.
Protected Attributes inherited from FFWrapperPtr< AVCodecContext >
AVCodecContext * m_raw
 The wrapped pointer; owned by the derived class, not by this template.

Detailed Description

Frames must carry the encoder time base before they are passed to encode() or send(); a mismatch produces packets with meaningless timestamps rather than an error.

Examples
api2-decode-encode-video.cpp, api2-decode-filter-encode.cpp, api2-decode-overlay-encode.cpp, api2-hw-encode.cpp, api2-hw-scale.cpp, api2-hw-transcode.cpp, and api2-scale-video.cpp.

Constructor & Destructor Documentation

◆ VideoEncoderContext()

av::VideoEncoderContext::VideoEncoderContext ( VideoEncoderContext && other)
Parameters
otherthe encoder to move from; left empty

Member Function Documentation

◆ configureHwEncoding() [1/2]

void av::VideoEncoderContext::configureHwEncoding ( const hw::DeviceContext & device,
hw::EncodingMode mode = hw::EncodingMode::Auto,
PixelFormat swFormat = AV_PIX_FMT_NONE,
OptionalErrorCode ec = throws() )
Parameters
devicehardware device. It must match the encoder.
modeAuto prefers a frames context, Frames requires it, Device uses AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX.
swFormatsoftware pixel format for a frames context. When AV_PIX_FMT_NONE, the current pixel format or the first format from FrameConstraints::swFormats() is used.

Auto creates a frames context when the codec has a frames configuration. It falls back to a device context when frames creation fails and a device configuration exists. Otherwise it reports HardwareConfigNotFound.

Parameters
ec
Examples
api2-hw-scale.cpp, and api2-hw-transcode.cpp.

◆ configureHwEncoding() [2/2]

void av::VideoEncoderContext::configureHwEncoding ( const hw::FramesContext & frames,
OptionalErrorCode ec = throws() )

Sets hw_frames_ctx and the hardware pixel format, and disables automatic upload. The encoder expects hardware frames from this context.

Parameters
frames
ec

◆ encode() [1/2]

Packet av::VideoEncoderContext::encode ( const VideoFrame & inFrame,
OptionalErrorCode ec = throws() )
Note
Some encoders need some amount of frames before beginning encoding, so it is normal, that for some amount of frames returns empty packets.
Parameters
inFrameframe to encode
[in,out]ecthis represents the error status on exit, if this is pre-initialized to av::throws the function will throw on error instead
Returns

◆ encode() [2/2]

Packet av::VideoEncoderContext::encode ( OptionalErrorCode ec = throws())

Stop flushing when returns empty packets

Parameters
[in,out]ecthis represents the error status on exit, if this is pre-initialized to av::throws the function will throw on error instead
Returns
Examples
api2-decode-encode-video.cpp, api2-decode-filter-encode.cpp, api2-decode-overlay-encode.cpp, api2-hw-scale.cpp, api2-hw-transcode.cpp, and api2-scale-video.cpp.

◆ hwDeviceContext()

hw::DeviceContext av::VideoEncoderContext::hwDeviceContext ( ) const
noexcept
Returns
the device set by configureHwEncoding() or setHwDeviceContext(), or an invalid value when encoding on the CPU

◆ hwEncodingMode()

hw::EncodingMode av::VideoEncoderContext::hwEncodingMode ( ) const
noexcept
Returns
the mode chosen by configureHwEncoding()

◆ hwFramesContext()

hw::FramesContext av::VideoEncoderContext::hwFramesContext ( ) const
noexcept
Returns
the pool set by configureHwEncoding(const hw::FramesContext&) or setHwFramesContext(), or an invalid value when there is none
Examples
api2-hw-scale.cpp.

◆ isHwAutoUpload()

bool av::VideoEncoderContext::isHwAutoUpload ( ) const
noexcept
Returns
the value set by setHwAutoUpload(); enabled by default

◆ isHwEncoding()

bool av::VideoEncoderContext::isHwEncoding ( ) const
noexcept
Returns
true when a device or a frames context is attached

◆ operator=()

VideoEncoderContext & av::VideoEncoderContext::operator= ( VideoEncoderContext && other)
Parameters
otherthe encoder to move from; left empty
Returns
this encoder

◆ receive()

Packet av::VideoEncoderContext::receive ( OptionalErrorCode ec = throws())

Returns an empty packet when no packet is available yet (EAGAIN) and when the stream has ended. Use isEof() to distinguish the two cases.

Parameters
echolder for the error code
Returns
the encoded packet, or an empty packet as described above

◆ send()

bool av::VideoEncoderContext::send ( const VideoFrame & frame,
OptionalErrorCode ec = throws() )
Parameters
framethe frame to encode
echolder for the error code
Returns
false if the encoder cannot accept more input until receive() is called. This EAGAIN condition is not an error.

◆ setHwAutoUpload()

void av::VideoEncoderContext::setHwAutoUpload ( bool enabled)
noexcept

Enabled by default. The function is used only when a hardware frames context is configured and the incoming frame is a software frame.

Parameters
enabled

◆ setHwDeviceContext()

void av::VideoEncoderContext::setHwDeviceContext ( const hw::DeviceContext & device,
OptionalErrorCode ec = throws() )
Parameters
device
ec

◆ setHwFramesContext()

void av::VideoEncoderContext::setHwFramesContext ( const hw::FramesContext & frames,
OptionalErrorCode ec = throws() )

The encoder will expect hardware frames. Use this for the zero-copy path: pass the frames context obtained from a decoded VideoFrame.

Parameters
frames
ec

The documentation for this class was generated from the following file: