avcpp 3.1.0
Wrapper for the FFmpeg that simplify usage from C++ projects.
Loading...
Searching...
No Matches
Decoding

Decoding turns compressed packets into frames. In avcpp the input side is av::Packet, the output side is av::VideoFrame or av::AudioSamples, and the state in between is a decoder context.

The shape of the loop

A decoder has an input queue and an output queue, and the two are not in lockstep: one packet can produce several frames, and a frame can be produced long after its packet was accepted. The contract is:

  1. send(packet) returns true when the packet was accepted, false when the decoder wants its output drained first.
  2. receive() returns a frame, or an empty value when there is nothing to read right now.
  3. At end of stream, flush() switches the decoder to draining mode, and receive() keeps returning frames until it returns an empty value for good. isEof() then becomes true.

The reference implementation is example/api2-samples/api2-send-receive.cpp:

auto drain = [&]() -> bool {
for (;;) {
auto frame = dec.receive(ec);
if (ec) {
std::cerr << "Can't receive a frame: " << ec.message() << '\n';
return false;
}
if (!frame)
return true;
++frames;
}
};
while ((pkt = ictx.readPacket(ec))) {
if (pkt.streamIndex() != vst.index())
continue;
++packets;
for (;;) {
bool accepted = dec.send(pkt, ec);
if (ec) {
std::cerr << "Can't send a packet: " << ec.message() << '\n';
return 1;
}
// Drain what is available. A rejected send() means EAGAIN: the
// packet must be retried after the output queue is empty.
if (!drain())
return 1;
if (accepted)
break;
}
}
if (ec) {
std::cerr << "Read error: " << ec.message() << '\n';
return 1;
}

Note what the loop does not assume: it never takes one packet to mean one frame, and it never treats an empty receive() as an error. An empty result means "nothing available", not "end of stream".

Setting up

ictx.openInput(argv[1], 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 &&st : ictx.streams()) {
if (st.mediaType() == AVMEDIA_TYPE_VIDEO) {
vst = st;
break;
}
}
if (!vst.isValid()) {
std::cerr << "Video stream not found\n";
return 1;
}
dec.open(ec);
if (ec) {
std::cerr << "Can't open codec: " << ec.message() << '\n';
return 1;
}

VideoDecoderContext can be constructed from a stream, which takes the codec from the stream parameters, or from a Codec when the codec has to be chosen explicitly (hardware decoding does that, see Hardware decoding and encoding).

Two settings are worth knowing before open():

  • setRefCountedFrames(true) makes the decoder hand out reference-counted frames. Copying such a frame is cheap, and it stays valid after the next receive() call. Without it, the frame buffer belongs to the decoder and is reused.
  • open() accepts an options dictionary: dec.open({{"threads", "4"}}, av::Codec(), ec) sets the decoder thread count, as example/api2-samples/api2-decode.cpp does.

Flushing

// Switch the decoder to draining mode. flush() is idempotent and reports
// false only when the output queue must be drained before it is retried.
if (!dec.flush(ec)) {
if (ec) {
std::cerr << "Can't flush the decoder: " << ec.message() << '\n';
return 1;
}
if (!drain())
return 1;
if (!dec.flush(ec)) {
std::cerr << "Can't flush the decoder after draining\n";
return 1;
}
}
if (!drain())
return 1;

flush() returns false when the output queue has to be drained before the switch to draining mode can complete; retrying it after the drain() lambda of the example is the correct response, and it is idempotent. Skipping the flush silently loses the last frames of every file, which is easy to miss because the count is usually small.

Timestamps

A frame carries a presentation timestamp (pts()) and a time base (timeBase()). The timestamp is in time base units, so seconds are pts().seconds(), and pts() is a av::Timestamp you can compare, convert and print directly.

Do not mix timestamps from different contexts: the decoder, the encoder and each stream have their own time base. When a frame is passed to another component, set the time base explicitly with frame.setTimeBase().

The legacy path

Older code uses decode(packet), which returns at most one frame per call and leaves the rest in the decoder:

while (Packet pkt = ictx.readPacket(ec)) {
if (ec) {
clog << "Packet reading error: " << ec << ", " << ec.message() << endl;
return 1;
}
if (pkt.streamIndex() != videoStream) {
continue;
}
auto ts = pkt.ts();
clog << "Read packet: " << ts << " / " << ts.seconds() << " / " << pkt.timeBase() << " / st: " << pkt.streamIndex() << endl;
#if AVCPP_HAS_PKT_SIDE_DATA
for (auto side : pkt.sideData()) {
clog << " found packet side data: " << side.name() << endl;
if (side.type() == AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL) {
assert(side.span().size() >= sizeof(uint64_t));
// BE
uint64_t idType{};
memcpy(&idType, side.span().data(), sizeof(idType));
//idType = std::endian::native == std::endian::little ? std::byteswap(idType) : idType;
idType = av_be2ne64(idType);
auto payload = side.span().subspan(sizeof(uint64_t));
clog << " matroska block additions id type = " << idType << endl;
if (!payload.empty() && idType == 100 /* vendor specific */) {
clog << " block additions data: " << std::string_view{(const char*)payload.data(), payload.size()} << endl;
}
}
}
#endif
VideoFrame frame = vdec.decode(pkt, ec);
count++;
//if (count > 100)
// break;
if (ec) {
cerr << "Error: " << ec << ", " << ec.message() << endl;
return 1;
} else if (!frame) {
cerr << "Empty frame\n";
//continue;
}
ts = frame.pts();
clog << " Frame: " << frame.width() << "x" << frame.height() << ", size=" << frame.size() << ", ts=" << ts << ", tm: " << ts.seconds() << ", tb: " << frame.timeBase() << ", ref=" << frame.isReferenced() << ":" << frame.refCount() << endl;
}

This still works for software decoders, and it is what example/api2-samples/api2-decode.cpp demonstrates. Do not use it with asynchronous hardware decoders, where a packet may produce its frame much later: the frame would be dropped. Use send()/receive() everywhere.

Audio

Audio decoding is the same flow with av::AudioDecoderContext and av::AudioSamples. Samples come as planar or packed data depending on the sample format; sampleFormat(), channelsCount(), sampleRate() and isPlanar() describe the layout, and av::AudioResampler converts between layouts when a consumer needs something else.

Next