|
avcpp 3.1.0
Wrapper for the FFmpeg that simplify usage from C++ projects.
|
This page describes the av::hw API. It gives safe and convenient access to the FFmpeg hardware codecs.
It answers the following questions:
The audience is avcpp developers and authors of applications built on avcpp.
The generated reference for these types is the Hardware acceleration group.
| Term | Meaning |
|---|---|
| Device | A hardware node: a GPU, a media block, a video card. In FFmpeg this is AVHWDeviceContext. |
| Frame pool | A set of surfaces of one size and format. In FFmpeg this is AVHWFramesContext. |
| Surface | A frame in device memory. The application does not read it directly. |
| System memory | Ordinary RAM. The frame is reachable through the data[] pointers. |
| Zero copy | A path on which the frame never leaves device memory. |
| Upload | Moving a frame from system memory into device memory. |
| Download | Moving a frame from device memory into system memory. |
| DeviceType | The device type: vaapi, qsv, cuda, d3d11va and others. |
| EncodingMode | The encoder mode: Auto, Frames, Device. |
Rule: one term means one concept. Do not use the word "buffer" for a device, a pool and a frame.
FFmpeg splits the hardware work into three layers.
The AVFrame layer holds the frame descriptor. When frame->hw_frames_ctx is not empty, the frame lives in device memory.
The layer diagram, with the corresponding avcpp types:
av::hw::DeviceContext and av::hw::FramesContext own the FFmpeg objects. A BufferRef lives inside. Copying the object adds a reference; destroying it drops one.
VideoFrame does not own the device. The frame holds a reference to the pool through hw_frames_ctx, and the pool holds a reference to the device through device_ref.
The ownership diagram:
Rules:
DeviceType is a thin wrapper over AVHWDeviceType.
Lookup is by name. The code does not depend on the numeric values of the enumeration, which matters for old FFmpeg versions.
DeviceContext is created by a factory. There is no constructor, because creating a device can fail.
Overloads:
derive() creates a derived device, for example an OpenCL device from a VAAPI device. Do not derive a device for QSV: it can crash.
The device parameter is a const char* or a std::string. That is deliberate: a device is not always a file.
The value depends on the backend:
std::filesystem::path implies a file and cannot express an index or an adapter name, which is why the API takes a string.
The const char* overload does not copy the string; the caller keeps it alive. The const std::string& overload keeps a copy inside the range.
initialPoolSize = 0 means the default pool size: FFmpeg picks it.
Methods:
swFormat is the format of the frame in system memory. Not every device supports NV12; check FrameConstraints::swFormats().
The API returns ranges. A range does not allocate memory and does not copy the array.
| Function | Type | Memory owner |
|---|---|---|
| allDeviceTypes() | DeviceTypeRange | FFmpeg |
| probeDevices(device) | DeviceProbeRange | FFmpeg, probed while iterating |
| frameConstraints(device, ec) | FrameConstraints | the owning object |
| FrameConstraints::hwFormats() | PixelFormatRange | FrameConstraints |
| FrameConstraints::swFormats() | PixelFormatRange | FrameConstraints |
| codecConfigs(codec) | CodecConfigRange | FFmpeg |
| findDecoders(id, type) | CodecRange | FFmpeg |
| findEncoders(id, type) | CodecRange | FFmpeg |
| FramesContext::transferFormats() | PixelFormatList | the owning object |
PixelFormatList owns an AVPixelFormat* array. range() returns a non-owning view; the list itself can be iterated directly.
Example:
probeDevices() creates a temporary device for every type. That is the only reliable check: av_hwdevice_iterate_types() enumerates the compiled-in backends, not the hardware that is present.
codecConfigs(codec) returns the list of AVCodecHWConfig. Each entry says which device type and which format the codec supports.
findCodecConfig(codec, type, methodsMask) returns the first matching entry.
findDecoder(id, type) and findEncoder(id, type) look a codec up by identifier and device type. The function walks every codec with that identifier, which matters for QSV: the generic h264 codec does not support QSV, h264_qsv does.
findDecoders() and findEncoders() return a lazy range. The range does not allocate.
FrameConstraints owns the FFmpeg structure. hwFormats() and swFormats() return non-owning views.
Some backends report very wide bounds, from 0x0 to INT_MAX. Do not treat those numbers as the exact limits of the hardware.
The sequence:
Example:
Do not use the legacy decode() with a hardware decoder when you need every frame: asynchronous backends such as QSV can return a frame later. The send()/receive() path drains them all. Do not forget flush().
By default a hardware decoder returns frames on the device, which is what zero copy needs.
When the application needs the data[] pointers, enable the automatic transfer:
receive() then returns frames in system memory. A decoder cannot be switched between the two modes in the middle of a stream: pick the mode before open().
The decoder sets only hw_device_ctx. The static get_format callback reads that field and derives the device type. AVCodecContext::opaque is not used, so the application is free to use it for its own purposes.
Some decoders, for example QSV in FFmpeg 4.x, advertise only AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX. avcpp creates a frame pool for them before open(), taking the size from coded_width and coded_height and the format from the device constraints. Without that pool, FFmpeg 4.x silently falls back to system memory.
There is no silent fallback to the software decoder: when the hardware path is impossible, the API returns an error, so the application learns about the problem immediately.
EncodingMode selects how frames reach the encoder.
| Mode | Meaning |
|---|---|
| Auto | A frame pool first; if the pool cannot be created, the device. |
| Frames | A frame pool only. Requires AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX. |
| Device | The device only. Requires AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX. |
Auto is the recommended mode for new code.
The sequence:
Example:
swFormat = AV_PIX_FMT_NONE enables format selection. The order is:
Automatic upload is on by default. When the input frame is in system memory, encode() uploads it into the pool first and then hands it to the encoder.
To disable it:
Disable it only for an explicit zero-copy path. Otherwise the encoder receives a frame of the wrong kind.
Some encoders need the frame rate before open(), QSV for example. Without it QSV fails with "Current frame rate is unsupported".
The decoder creates a pool of surfaces. The encoder uses the same pool. The frame never leaves the device.
FFmpeg's own vaapi_transcode.c example uses this approach, and it works for VAAPI, QSV and CUDA.
The diagram:
av_hwframe_map() is not a reliable path between different contexts: some backends return ENOSYS, and a derived QSV pool can crash.
The correct path is to take the pool from the decoder's first frame and hand it to the encoder.
When the pool is not available, use the copying path:
The api2-hw-transcode example makes this choice automatically.
VideoRescaler works with system memory. A fully hardware pipeline that changes the size needs an intermediate download.
The path:
The diagram:
Example: api2-hw-scale.
Note that a transfer between system memory and the device costs time. Measure both paths on the target hardware; with small frames the software pipeline is sometimes faster.
VideoFrame provides four operations.
| Method | Direction | Notes |
|---|---|---|
| toSystemMemory(format, ec) | device → system | format = AV_PIX_FMT_NONE picks the format automatically |
| toHwFrame(frames, ec) | system → device | Calls av_hwframe_get_buffer() first |
| mapTo(frames, flags, ec) | mapping | Backend dependent, can return ENOSYS |
| hwFramesContext() | query | Returns the frame's pool |
| hwDeviceContext() | query | Returns the pool's device |
toHwFrame() allocates a surface in the pool first and then calls av_hwframe_transfer_data(). Calling av_hwframe_transfer_data() directly without a surface returns EINVAL on some backends.
VideoFrame::clone() does not clone a hardware frame: it returns HardwareTransferUnsupported. Copying a surface is not cheap. When a second owner is needed, copy the VideoFrame object instead; the copy adds a reference to the AVFrame.
After a transfer or a rescale, set the timestamp and the stream index explicitly. The new object does not always inherit m_timeBase from the avcpp wrapper.
| Platform | Main types | Probe only |
|---|---|---|
| Linux | vaapi, qsv, cuda, vdpau | opencl, vulkan, drm |
| Windows | d3d11va, dxva2, qsv, cuda, amf | opencl, vulkan |
| macOS | videotoolbox | — |
| Android | mediacodec | — |
"Probe only" means the type is useful for checking a device or a pool; there is no tested hardware codec for it.
QSV needs its own codec; the generic h264 does not work.
The QSV encoder needs setFrameRate() before open(). The QSV decoder can return the first frames late; use send() and receive().
QSV with FFmpeg 4.x goes through libmfx, and that combination is incomplete in ubuntu:22.04:
The same commands in ffmpeg(1) behave the same way, so this is a limitation of the environment, not of avcpp. The tests skip these steps and print a warning. Use VAAPI to exercise Intel hardware on FFmpeg 4.x. Since FFmpeg 5.0, QSV goes through oneVPL and does not have these limitations.
| Code | Cause | Action |
|---|---|---|
| HardwareDeviceUnavailable | The device cannot be created | Check the driver and the device name |
| HardwareDeviceInvalid | An empty or invalid DeviceContext | Create the device again |
| HardwareConfigNotFound | The codec does not support the device | Pick another codec or mode |
| HardwareFramesInvalid | The pool was not created | Check the format, the size and the constraints |
| HardwareTransferUnsupported | The transfer is impossible | Use system memory |
| HardwareCodecNotFound | No hardware codec | Use a software codec |
| CodecAlreadyOpened | Configuration after open() | Configure the codec before open() |
Every function takes an OptionalErrorCode. By default an error throws; pass a std::error_code when you want the code back.
| FFmpeg | avcpp |
|---|---|
| AVHWDeviceType | av::hw::DeviceType |
| AVHWDeviceContext | av::hw::DeviceContext |
| AVHWFramesContext | av::hw::FramesContext |
| AVHWFramesConstraints | av::hw::FrameConstraints |
| AVCodecHWConfig | av::hw::codecConfigs() |
| av_hwdevice_iterate_types() | av::hw::allDeviceTypes() |
| av_hwdevice_ctx_create() | DeviceContext::create() |
| av_hwdevice_ctx_create_derived_opts() | DeviceContext::derive() |
| av_hwframe_ctx_alloc() + av_hwframe_ctx_init() | FramesContext::create() |
| av_hwframe_transfer_get_formats() | FramesContext::transferFormats() |
| av_hwframe_get_buffer() + av_hwframe_transfer_data() | VideoFrame::toHwFrame() |
| av_hwframe_transfer_data() into system memory | VideoFrame::toSystemMemory() |
| av_hwframe_map() | VideoFrame::mapTo() |
| avcodec_get_hw_config() | av::hw::codecConfigs() |
The minimum version is FFmpeg 4.0.
The tests live in tests/Hardware.cpp and tests/Fixtures.cpp. They must not fail on a machine without hardware.
The rule:
Environment variables:
The variables also affect the fixture tests.
The default set:
Commands:
Verified:
Docker verification:
Without nvidia-container-toolkit the --gpus all flag does not work; pass the devices and the driver libraries through by hand.
Limit the container memory and set a timeout. The QSV test on FFmpeg 4.x exhausts memory without those measures.
In example/api2-samples:
| Example | Purpose |
|---|---|
| api2-hw-probe | List devices, constraints and codec configurations |
| api2-hw-decode | Hardware decoding, with and without transfer |
| api2-hw-encode | Synthetic frames and a hardware encoder |
| api2-hw-transcode | Transcoding without copying, plus the fallback path |
| api2-hw-scale | Hardware decoding, scaling, encoding |
Running them: