avcpp 3.2.1
Wrapper for the FFmpeg that simplify usage from C++ projects.
Loading...
Searching...
No Matches
api2-hw-scale.cpp

Hardware scaling pipeline.

Hardware scaling pipeline.

api2-hw-scale <device type> <input file> <output file>
// Full hardware pipeline with a software rescale step.
//
// Usage: api2-hw-scale <device> <input> <output>
//
// The sample decodes on the GPU, transfers every frame to system memory,
// rescales it with libswscale and uploads it back to the GPU for encoding.
// The output is half the input size.
#include <iostream>
#include <memory>
#include <string>
#include "avcpp/av.h"
#include "avcpp/format.h"
#include "avcpp/packet.h"
#include "avcpp/stream.h"
int main(int argc, char** argv)
{
if (argc < 4) {
std::cerr << "Usage: " << argv[0] << " <device> <input> <output>\n";
return 1;
}
if (type.isNone()) {
std::cerr << "Unknown device type: " << argv[1] << '\n';
return 1;
}
std::error_code ec;
av::hw::DeviceContext device = av::hw::DeviceContext::create(type, nullptr, {}, ec);
if (!device.isValid()) {
std::cerr << "Can't create device: " << ec.message() << '\n';
return 2;
}
ictx.openInput(argv[2], ec);
if (ec) {
std::cerr << "Can't open input: " << ec.message() << '\n';
return 1;
}
ictx.findStreamInfo(ec);
if (ec) {
std::cerr << "Can't find streams: " << ec.message() << '\n';
return 1;
}
for (auto&& stream : ictx.streams()) {
if (stream.mediaType() == AVMEDIA_TYPE_VIDEO) {
vst = stream;
break;
}
}
if (!vst.isValid()) {
std::cerr << "Video stream not found\n";
return 1;
}
const AVCodecID codecId = vst.codecParameters().codecId();
av::Codec decoderCodec = av::hw::findDecoder(codecId, type);
av::Codec encoderCodec = av::hw::findEncoder(codecId, type);
if (!decoderCodec.raw() || !encoderCodec.raw()) {
std::cerr << "No hardware decoder or encoder for this codec and device\n";
return 2;
}
av::VideoDecoderContext decoder(vst, decoderCodec);
decoder.setHwDeviceContext(device, ec);
decoder.open(av::Codec(), ec);
if (ec) {
std::cerr << "Can't open decoder: " << ec.message() << '\n';
return 1;
}
const int dstWidth = (decoder.width() / 2) & ~1;
const int dstHeight = (decoder.height() / 2) & ~1;
if (dstWidth <= 0 || dstHeight <= 0) {
std::cerr << "Input frame is too small to rescale\n";
return 1;
}
ofrmt.setFormat(std::string(), argv[3]);
octx.setFormat(ofrmt);
av::VideoEncoderContext encoder(encoderCodec);
encoder.setWidth(dstWidth);
encoder.setHeight(dstHeight);
encoder.setTimeBase(av::Rational{1, 1000});
encoder.setFrameRate(vst.frameRate());
encoder.setBitRate(decoder.bitRate());
if (octx.outputFormat().isFlags(AVFMT_GLOBALHEADER))
encoder.addFlags(AV_CODEC_FLAG_GLOBAL_HEADER);
// Auto mode creates a hardware frames context. Its software format is the
// format that the rescaler must produce for the upload.
AV_PIX_FMT_NONE, ec);
if (ec) {
std::cerr << "Can't configure hardware encoding: " << ec.message() << '\n';
return 1;
}
const av::hw::FramesContext hwFrames = encoder.hwFramesContext();
if (!hwFrames.isValid()) {
std::cerr << "Hardware frames context is not available\n";
return 1;
}
encoder.open(encoderCodec, ec);
if (ec) {
std::cerr << "Can't open encoder: " << ec.message() << '\n';
return 1;
}
av::Stream ost = octx.addStream(encoder);
ost.setFrameRate(vst.frameRate());
ost.setTimeBase(encoder.timeBase());
octx.openOutput(argv[3], ec);
if (ec) {
std::cerr << "Can't open output: " << ec.message() << '\n';
return 1;
}
octx.writeHeader(ec);
octx.flush();
if (ec) {
std::cerr << "Can't write header: " << ec.message() << '\n';
return 1;
}
std::cout << "pipeline: " << decoderCodec.name() << " -> system memory -> "
<< dstWidth << 'x' << dstHeight << " -> " << encoderCodec.name() << '\n';
std::unique_ptr<av::VideoRescaler> rescaler;
std::size_t frames = 0;
int64_t index = 0;
// Decoded frame -> system memory -> rescale -> hardware upload -> encode.
auto process = [&](av::VideoFrame hardware) -> bool {
const av::Timestamp sourceTimestamp = hardware.pts();
av::VideoFrame software = hardware.toSystemMemory(AV_PIX_FMT_NONE, ec);
if (ec) {
std::cerr << "Can't transfer frame to system memory: "
<< ec.message() << '\n';
return false;
}
if (!rescaler) {
rescaler = std::make_unique<av::VideoRescaler>(
dstWidth, dstHeight, hwFrames.swFormat(),
software.width(), software.height(), software.pixelFormat());
}
av::VideoFrame scaled = rescaler->rescale(software, ec);
if (ec) {
std::cerr << "Rescale error: " << ec.message() << '\n';
return false;
}
av::VideoFrame uploaded = scaled.toHwFrame(hwFrames, ec);
if (ec) {
std::cerr << "Can't upload frame to hardware: " << ec.message() << '\n';
return false;
}
// The transfer and rescale create new wrapper objects, so assign the
// output timing explicitly. This keeps the encoder timestamps valid.
uploaded.setTimeBase(encoder.timeBase());
uploaded.setStreamIndex(0);
if (sourceTimestamp.isValid() && !sourceTimestamp.isNoPts())
uploaded.setPts(sourceTimestamp);
else
uploaded.setPts(av::Timestamp(index, encoder.timeBase()));
++index;
av::Packet output = encoder.encode(uploaded, ec);
if (ec) {
std::cerr << "Encode error: " << ec.message() << '\n';
return false;
}
if (!output)
return true;
output.setStreamIndex(0);
octx.writePacket(output, ec);
if (ec) {
std::cerr << "Write error: " << ec.message() << '\n';
return false;
}
++frames;
return true;
};
av::Packet packet;
while ((packet = ictx.readPacket(ec))) {
if (packet.streamIndex() != vst.index())
continue;
for (;;) {
const bool accepted = decoder.send(packet, ec);
if (ec) {
std::cerr << "Send error: " << ec.message() << '\n';
return 1;
}
for (;;) {
av::VideoFrame hardware = decoder.receive(ec);
if (ec) {
std::cerr << "Receive error: " << ec.message() << '\n';
return 1;
}
if (!hardware.isValid())
break;
if (!process(std::move(hardware)))
return 1;
}
if (accepted)
break;
}
}
if (ec) {
std::cerr << "Read error: " << ec.message() << '\n';
return 1;
}
// Hardware decoders delay frames, so drain them after the last packet.
if (!decoder.flush(ec)) {
std::cerr << "Flush error: " << ec.message() << '\n';
return 1;
}
for (;;) {
av::VideoFrame hardware = decoder.receive(ec);
if (ec) {
std::cerr << "Receive error: " << ec.message() << '\n';
return 1;
}
if (!hardware.isValid())
break;
if (!process(std::move(hardware)))
return 1;
}
for (;;) {
av::Packet output = encoder.encode(ec);
if (ec) {
std::cerr << "Encoder flush error: " << ec.message() << '\n';
return 1;
}
if (!output)
break;
output.setStreamIndex(0);
octx.writePacket(output, ec);
if (ec) {
std::cerr << "Write error: " << ec.message() << '\n';
return 1;
}
++frames;
}
octx.writeTrailer(ec);
if (ec) {
std::cerr << "Can't write trailer: " << ec.message() << '\n';
return 1;
}
std::cout << "frames: " << frames << '\n';
return 0;
}
Library initialization.
int64_t bitRate() const noexcept
Target bit rate.
void setFrameRate(const Rational &value) noexcept
Set the frame rate.
Rational timeBase() const noexcept
Time base of the codec.
void setBitRate(int64_t bitRate) noexcept
Set the target bit rate.
void open(OptionalErrorCode ec=throws())
Open the codec with the parameters set so far.
void addFlags(int flags) noexcept
Add AV_CODEC_FLAG_* flags.
void setTimeBase(const Rational &value) noexcept
Set the time base.
bool flush(OptionalErrorCode ec=throws())
Puts the codec into draining mode.
Definition codeccontext.h:863
AVCodecID codecId() const
Identifier of the codec.
Codec descriptor.
Definition codec.h:32
const char * name() const
Short name of the codec, as FFmpeg knows it.
Container context: the entry point for demuxing, muxing and seeking.
Definition formatcontext.h:153
StreamsView streams(OptionalErrorCode ec=throws()) const
All streams as a range, for range-based for and std algorithms.
OutputFormat outputFormat() const
The muxer in use.
void openInput(const std::string &uri, OptionalErrorCode ec=throws())
Open an input and probe its container.
Stream addStream(const Codec &codec, OptionalErrorCode ec=throws())
Add a stream for the given codec.
void writeTrailer(OptionalErrorCode ec=throws())
Write the container trailer and close the output.
void writeHeader(OptionalErrorCode ec=throws())
Write the container header.
void openOutput(const std::string &uri, OptionalErrorCode ec=throws())
Open an output.
void writePacket(OptionalErrorCode ec=throws())
Flush the muxer queue.
void flush()
Discard buffered packets and internal state.
void setFormat(const InputFormat &format)
Force the demuxer used by openInput().
void findStreamInfo(OptionalErrorCode ec=throws())
Read the stream parameters of an opened input.
Packet readPacket(OptionalErrorCode ec=throws())
Read the next packet from any stream.
attribute_deprecated void setPts(int64_t pts, Rational ptsTimeBase)
Set the timestamp and its time base at once.
bool isValid() const
Whether the wrapper holds a frame.
void setTimeBase(const Rational &value)
Set the time base.
void setStreamIndex(int streamIndex)
Set the stream index.
Muxer descriptor.
Definition format.h:202
bool setFormat(const std::string &name, const std::string &url=std::string(), const std::string &mime=std::string()) noexcept
Look a muxer up and point the descriptor at it.
Compressed data and its metadata.
Definition packet.h:110
int streamIndex() const
Index of the stream the packet belongs to.
void setStreamIndex(int idx)
Set the stream index.
Rational number: a numerator and a denominator.
Definition rational.h:49
One stream inside a container.
Definition stream.h:34
CodecParametersView codecParameters() const
Codec parameters of the stream.
void setFrameRate(const Rational &frameRate)
Set the declared frame rate.
Rational frameRate() const
Frame rate declared by the stream.
int index() const
Position of the stream in its container.
bool isValid() const
Whether the view refers to a stream.
void setTimeBase(const Rational &timeBase)
Set the time base of the stream.
void setAverageFrameRate(const Rational &frameRate)
Set the average frame rate.
The Timestamp class represents timestamp value and it timebase.
Definition timestamp.h:25
bool isNoPts() const noexcept
Whether the timestamp means "no timestamp".
bool isValid() const noexcept
Whether the timestamp is usable.
int height() const
Frame height stored in the context.
Definition codeccontext.h:940
void setWidth(int w)
Set the frame width.
Definition codeccontext.h:1033
void setHeight(int h)
Set the frame height.
Definition codeccontext.h:1049
int width() const
Frame width stored in the context.
Definition codeccontext.h:930
Decodes video packets into frames.
Definition codeccontext.h:1161
bool send(const Packet &packet, OptionalErrorCode ec=throws())
Sends a packet to the decoder.
VideoFrame receive(OptionalErrorCode ec=throws(), bool autoAllocateFrame=true)
Receives one decoded frame.
void setHwDeviceContext(const hw::DeviceContext &device, OptionalErrorCode ec=throws())
Configures a hardware device for decoding.
Encodes video frames into packets.
Definition codeccontext.h:1338
Packet encode(OptionalErrorCode ec=throws())
encodeVideo - Flush 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.
hw::FramesContext hwFramesContext() const noexcept
Frames context configured for this encoder.
One video frame.
Definition frame.h:578
VideoFrame toHwFrame(const hw::FramesContext &frames, OptionalErrorCode ec=throws()) const
Upload a software frame into hardware memory.
VideoFrame toSystemMemory(PixelFormat format=AV_PIX_FMT_NONE, OptionalErrorCode ec=throws()) const
Transfer a hardware frame into system memory.
int height() const
Frame height.
int width() const
Frame width.
PixelFormat pixelFormat() const
Pixel format of the frame.
Owner of an AVHWDeviceContext.
Definition hwcontext.h:126
bool isValid() const noexcept
Whether the wrapper holds a device.
static DeviceContext create(DeviceType type, const char *device=nullptr, const Dictionary &options={}, OptionalErrorCode ec=throws())
Create and open a hardware device.
Wrapper for AVHWDeviceType.
Definition hwcontext.h:53
static DeviceType fromName(const char *name) noexcept
Look a device type up by its FFmpeg name.
bool isNone() const noexcept
Whether the wrapper holds no device type.
Definition hwcontext.h:84
Owner of an AVHWFramesContext.
Definition hwcontext.h:242
bool isValid() const noexcept
Whether the wrapper holds a pool.
PixelFormat swFormat() const noexcept
The system-memory format used to transfer frames into and out of the pool.
Codec contexts: opening, configuring, encoding and decoding.
Input and output format descriptors.
Container format contexts: opening, demuxing, muxing and seeking.
Hardware devices, hardware frames and hardware codec configuration.
Codec findEncoder(AVCodecID id, DeviceType type) noexcept
The first encoder for a codec identifier that supports a device type.
@ Auto
Prefer a hardware frames context, fall back to a device context.
Definition hwcontext.h:37
Codec findDecoder(AVCodecID id, DeviceType type) noexcept
The first decoder for a codec identifier that supports a device type.
void init()
Initialize all subsystems the library needs.
Compressed packets and their side data.
Streams inside a container: parameters, time base and disposition.
const T * raw() const
Read access to the wrapped object.
Definition ffmpeg.h:56
bool isFlags(int32_t flags) const noexcept
Whether all given flags are set.
Definition format.h:112
Video scaling and pixel format conversion with libswscale.