Decode call video through bounded submit/drain with verified GPU and four CPU slice threads

This commit is contained in:
evgeny committed 2026-10-19 19:06:52 +02:00
1 parent 18e81c3c81
commit 50528e1bad
2 files changed
+211 -75

No files matched your search

+198 -72
View File
@@ -2,106 +2,232 @@
#include "video_frame_image.h"
#include "debug_config.h"
#include "../../../src/call/call_video_bitstream.h"
#include "../../../src/call/call_video_playout.h"
#include <QTransform>
#include <QThread>
#include <atomic>
#include <deque>
#include <mutex>
#ifdef HAVE_FFMPEG
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
#include <libavutil/hwcontext.h>
#include <libswscale/swscale.h>
}
namespace {
std::atomic<unsigned> gpuProfiles[2]{};
std::atomic<unsigned> gpuPipeline[2]{};
QString ffError(int value) { char text[AV_ERROR_MAX_STRING_SIZE]; av_strerror(value, text, sizeof(text)); return text; }
#ifdef _WIN32
constexpr AVHWDeviceType DeviceType = AV_HWDEVICE_TYPE_D3D11VA;
#else
constexpr AVHWDeviceType DeviceType = AV_HWDEVICE_TYPE_VAAPI;
#endif
}
#endif
struct CallVideoDecoder::Impl {
Backend backend = Backend::Automatic;
call_video_format format{};
std::deque<call_video_frame> pending;
QString error;
unsigned pipeline = 0;
bool gpu = false, eos = false, outputSeen = false;
#ifdef HAVE_FFMPEG
AVCodecContext* codec = nullptr;
AVPixelFormat pixel = AV_PIX_FMT_NONE;
SwsContext* scale = nullptr;
static AVPixelFormat getFormat(AVCodecContext* codec, const AVPixelFormat* formats) {
auto* self = static_cast<Impl*>(codec->opaque);
for (const auto* p = formats; *p != AV_PIX_FMT_NONE; ++p) if (*p == self->pixel) return *p;
DEBUG_ERROR(DEBUG_CATEGORY_CALL, "video GPU decoder pixel format unavailable expected=%d", self->pixel);
return AV_PIX_FMT_NONE;
}
int failed(const char* stage, int result) {
error = QString("Video decoder %1: %2").arg(stage, ffError(result));
DEBUG_ERROR(DEBUG_CATEGORY_CALL, "video decoder failed stage=%s backend=%s pending=%zu generation=%llu result=%d error=%s",
stage, gpu ? av_hwdevice_get_type_name(DeviceType) : "cpu", pending.size(),
(unsigned long long)format.generation, result, qPrintable(error)); return -1;
}
bool open(const call_video_format& f) {
format = f;
const AVCodec* implementation = avcodec_find_decoder(f.codec == CALL_VIDEO_H265 ? AV_CODEC_ID_HEVC : AV_CODEC_ID_H264);
codec = implementation ? avcodec_alloc_context3(implementation) : nullptr;
if (!codec) { failed("allocation", AVERROR(ENOMEM)); return false; }
gpu = backend == Backend::HardwareOnly || (backend == Backend::Automatic && (gpuProfiles[f.codec - 1].load() & f.profile));
codec->thread_count = gpu ? 1 : 4; codec->thread_type = FF_THREAD_SLICE;
codec->flags |= AV_CODEC_FLAG_LOW_DELAY; codec->pkt_timebase = {1, 1000000};
if (gpu) {
for (int i = 0; const auto* config = avcodec_get_hw_config(implementation, i); ++i)
if (config->device_type == DeviceType && (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX)) {
pixel = config->pix_fmt; break;
}
if (pixel == AV_PIX_FMT_NONE) { failed("hardware configuration unavailable", AVERROR(ENOSYS)); return false; }
int result = av_hwdevice_ctx_create(&codec->hw_device_ctx, DeviceType, nullptr, nullptr, 0);
if (result < 0) { failed("hardware device", result); return false; }
codec->opaque = this; codec->get_format = getFormat;
pipeline = gpuPipeline[f.codec - 1].load();
}
int result = avcodec_open2(codec, implementation, nullptr);
if (result < 0) { failed("open", result); return false; }
DEBUG_INFO(DEBUG_CATEGORY_CALL, "video decoder opened codec=%u name=%s backend=%s threads=%d thread_type=%d level=%u generation=%llu",
f.codec, implementation->name, gpu ? av_hwdevice_get_type_name(DeviceType) : "cpu", codec->thread_count,
codec->active_thread_type, f.level, (unsigned long long)f.generation); return true;
}
#endif
};
CallVideoDecoder::CallVideoDecoder() : m(std::make_unique<Impl>()) {}
CallVideoDecoder::CallVideoDecoder(Backend backend) : m(std::make_unique<Impl>()) { m->backend = backend; }
CallVideoDecoder::~CallVideoDecoder() { close(); }
unsigned CallVideoDecoder::pendingFrames() const { return static_cast<unsigned>(m->pending.size()); }
unsigned CallVideoDecoder::pipelineFrames() const { return m->pipeline; }
bool CallVideoDecoder::hardware() const { return m->gpu; }
QString CallVideoDecoder::error() const { return m->error; }
void CallVideoDecoder::close() {
#ifdef HAVE_FFMPEG
avcodec_free_context(&m->codec); sws_freeContext(m->scale); m->scale = nullptr;
if (m->codec) DEBUG_DEBUG(DEBUG_CATEGORY_CALL, "video decoder close generation=%llu pending=%zu eos=%d",
(unsigned long long)m->format.generation, m->pending.size(), m->eos);
avcodec_free_context(&m->codec); sws_freeContext(m->scale); m->scale = nullptr; m->pixel = AV_PIX_FMT_NONE;
#endif
m->format = {};
m->format = {}; m->pending.clear(); m->pipeline = 0; m->gpu = m->eos = m->outputSeen = false;
}
call_video_caps CallVideoDecoder::capabilities() {
call_video_caps caps{};
for (unsigned codec = 1; codec <= 2; ++codec) {
unsigned profiles = 0;
for (unsigned profile = 1; profile <= (codec == 1 ? 2u : 1u); ++profile) {
uint8_t bytes[8192]; int size = call_video_probe_key(codec, profile, bytes, sizeof(bytes));
if (size < 0) continue;
call_video_frame f{}; f.call_id = 1; f.flags = CALL_VIDEO_KEY; f.data = bytes; f.size = f.length = size;
f.format = {1, 1280, 720, 30, 0, (uint8_t)codec, (uint8_t)(codec == 1 ? 31 : 93), 4000000, (uint8_t)profile};
CallVideoDecoder decoder; bool valid = true;
for (unsigned i = 0; i < 4 && valid; ++i) {
f.frame_id = i + 1; f.pts_us = 1000000 + i * 33333;
QImage image; valid = decoder.decode(f, image);
}
if (valid) profiles |= profile;
else DEBUG_WARN(DEBUG_CATEGORY_CALL, "video independent decoder probe failed codec=%u profile=%u", codec, profile);
}
if (profiles) caps.decode[codec - 1] = {1280, 720, 30, 1280 * 720 * 30, 4000000,
(uint8_t)profiles, (uint8_t)(codec == 1 ? 31 : 93)};
DEBUG_INFO(DEBUG_CATEGORY_CALL, "video decoder probe codec=%u profiles=%u", codec, profiles);
}
return caps;
}
bool CallVideoDecoder::decode(const call_video_frame& f, QImage& image) {
int CallVideoDecoder::finish() {
#ifdef HAVE_FFMPEG
auto failed = [this, &f](const char* reason) {
DEBUG_WARN(DEBUG_CATEGORY_CALL, "video decode rejected frame=%llu generation=%llu reason=%s",
(unsigned long long)f.frame_id, (unsigned long long)f.format.generation, reason);
close(); return false;
};
if (!call_video_format_valid(&f.format) || !f.data || !f.size || f.size > CALL_VIDEO_MAX_FRAME) return failed("format");
bool changed = !call_video_same_format(&m->format, &f.format);
if (!m->codec || m->eos) return 1;
int result = avcodec_send_packet(m->codec, nullptr);
if (result == AVERROR(EAGAIN)) return 0;
if (result < 0 && result != AVERROR_EOF) return m->failed("EOS", result);
m->eos = true; return 1;
#else
return -1;
#endif
}
int CallVideoDecoder::submit(const call_video_frame& f) {
#ifdef HAVE_FFMPEG
if (!call_video_format_valid(&f.format) || !f.data || !f.size || f.size > CALL_VIDEO_MAX_FRAME)
return m->failed("input format", AVERROR_INVALIDDATA);
const uint8_t* data = f.data; unsigned size = f.size;
if (f.flags & CALL_VIDEO_KEY) {
if (call_video_check_key(&f.format, f.data, f.size)) return failed("bitstream contract");
if (size < 5) return failed("KEY envelope");
uint32_t config = (uint32_t)data[0] << 24 | (uint32_t)data[1] << 16 | (uint32_t)data[2] << 8 | data[3];
if (config > 65536 || config >= size - 4) return failed("KEY config length");
data += 4; size -= 4; // Annex B configuration и access unit подаются вместе.
} else if (changed || !m->codec) return failed("KEY required");
if (changed || !m->codec) {
close();
const AVCodec* codec = avcodec_find_decoder(f.format.codec == CALL_VIDEO_H265 ? AV_CODEC_ID_HEVC : AV_CODEC_ID_H264);
if (!codec || !(m->codec = avcodec_alloc_context3(codec))) return failed("decoder unavailable");
m->codec->thread_count = 1; m->codec->flags |= AV_CODEC_FLAG_LOW_DELAY;
if (avcodec_open2(m->codec, codec, nullptr) < 0) return failed("decoder open");
m->format = f.format;
DEBUG_INFO(DEBUG_CATEGORY_CALL, "video decoder opened codec=%u level=%u generation=%llu",
f.format.codec, f.format.level, (unsigned long long)f.format.generation);
if (call_video_check_key(&f.format, data, size)) return m->failed("KEY bitstream", AVERROR_INVALIDDATA);
data += 4; size -= 4;
}
AVPacket* packet = av_packet_alloc(); AVFrame* decoded = av_frame_alloc();
if (!packet || !decoded) { av_packet_free(&packet); av_frame_free(&decoded); return failed("allocation"); }
if (!call_video_same_format(&m->format, &f.format) || m->eos) {
if (!m->pending.empty()) { if (finish() < 0) return -1; return 0; }
if (!(f.flags & CALL_VIDEO_KEY)) return m->failed("KEY required", AVERROR_INVALIDDATA);
close(); if (!m->open(f.format)) return -1;
}
if (m->pending.size() >= 8) return 0;
AVPacket* packet = av_packet_alloc();
if (!packet) return m->failed("packet allocation", AVERROR(ENOMEM));
int result = av_new_packet(packet, size);
if (result >= 0) {
memcpy(packet->data, data, size); packet->pts = packet->dts = f.pts_us;
result = avcodec_send_packet(m->codec, packet);
if (result >= 0) result = avcodec_receive_frame(m->codec, decoded);
}
bool valid = result >= 0 && decoded->pts == f.pts_us && decoded->width == f.format.width && decoded->height == f.format.height
&& decoded->format == AV_PIX_FMT_YUV420P && !m->codec->has_b_frames && m->codec->level <= f.format.level;
int profile = f.format.codec == CALL_VIDEO_H265 ? AV_PROFILE_HEVC_MAIN : AV_PROFILE_H264_CONSTRAINED_BASELINE;
valid = valid && (m->codec->profile == profile || (f.format.codec == CALL_VIDEO_H264
&& f.format.profile == CALL_VIDEO_BASELINE && m->codec->profile == AV_PROFILE_H264_BASELINE));
if (valid) {
QImage output = video_frame_image(decoded->width, decoded->height);
m->scale = sws_getCachedContext(m->scale, decoded->width, decoded->height, AV_PIX_FMT_YUV420P,
decoded->width, decoded->height, AV_PIX_FMT_RGB24, SWS_FAST_BILINEAR, nullptr, nullptr, nullptr);
if (!m->scale || output.isNull()) valid = false;
else {
uint8_t* planes[4] = {output.bits(), nullptr, nullptr, nullptr}; int strides[4] = {(int)output.bytesPerLine(), 0, 0, 0};
valid = sws_scale(m->scale, decoded->data, decoded->linesize, 0, decoded->height, planes, strides) == decoded->height;
if (valid) image = f.format.rotation ? output.transformed(QTransform().rotate(f.format.rotation)) : output;
}
}
av_packet_free(&packet); av_frame_free(&decoded);
return valid ? true : failed("PTS/profile/level/geometry/output");
av_packet_free(&packet);
if (result == AVERROR(EAGAIN)) return 0;
if (result < 0) return m->failed("input", result);
m->pending.push_back(f); m->pending.back().data = nullptr;
return 1;
#else
Q_UNUSED(f); Q_UNUSED(image); DEBUG_WARN(DEBUG_CATEGORY_CALL, "video decoder unavailable: no FFmpeg"); return false;
Q_UNUSED(f); DEBUG_ERROR(DEBUG_CATEGORY_CALL, "video decoder unavailable: no FFmpeg"); return -1;
#endif
}
int CallVideoDecoder::receive(call_video_frame& f, QImage& image) {
#ifdef HAVE_FFMPEG
if (!m->codec) return 0;
AVFrame* decoded = av_frame_alloc(); AVFrame* copied = nullptr;
if (!decoded) return m->failed("frame allocation", AVERROR(ENOMEM));
int result = avcodec_receive_frame(m->codec, decoded);
if (result == AVERROR(EAGAIN) || result == AVERROR_EOF) {
av_frame_free(&decoded);
if (result == AVERROR_EOF && !m->pending.empty()) return m->failed("EOS lost accepted frames", AVERROR_INVALIDDATA);
return 0;
}
if (result >= 0 && (m->pending.empty() || decoded->pts != m->pending.front().pts_us)) result = AVERROR_INVALIDDATA;
if (result >= 0) {
f = m->pending.front();
int profile = f.format.codec == CALL_VIDEO_H265 ? AV_PROFILE_HEVC_MAIN : AV_PROFILE_H264_CONSTRAINED_BASELINE;
bool valid = decoded->width == f.format.width && decoded->height == f.format.height
&& !m->codec->has_b_frames && m->codec->level <= f.format.level
&& (m->codec->profile == profile || (f.format.codec == CALL_VIDEO_H264
&& f.format.profile == CALL_VIDEO_BASELINE && m->codec->profile == AV_PROFILE_H264_BASELINE));
if (!valid) result = AVERROR_INVALIDDATA;
}
AVFrame* pixels = decoded;
if (result >= 0 && m->gpu) {
copied = av_frame_alloc();
result = copied ? av_hwframe_transfer_data(copied, decoded, 0) : AVERROR(ENOMEM);
pixels = copied;
}
if (result >= 0 && pixels->format != AV_PIX_FMT_YUV420P && pixels->format != AV_PIX_FMT_NV12) result = AVERROR_INVALIDDATA;
if (result >= 0) {
QImage output = video_frame_image(pixels->width, pixels->height);
m->scale = sws_getCachedContext(m->scale, pixels->width, pixels->height, static_cast<AVPixelFormat>(pixels->format),
pixels->width, pixels->height, AV_PIX_FMT_RGB24, SWS_FAST_BILINEAR, nullptr, nullptr, nullptr);
if (!m->scale || output.isNull()) result = AVERROR(ENOMEM);
else {
uint8_t* planes[4] = {output.bits(), nullptr, nullptr, nullptr}; int strides[4] = {(int)output.bytesPerLine(), 0, 0, 0};
if (sws_scale(m->scale, pixels->data, pixels->linesize, 0, pixels->height, planes, strides) != pixels->height)
result = AVERROR_INVALIDDATA;
else image = f.format.rotation ? output.transformed(QTransform().rotate(f.format.rotation)) : output;
}
}
av_frame_free(&copied); av_frame_free(&decoded);
if (result < 0) return m->failed("output PTS/profile/geometry/transfer", result);
if (!m->outputSeen) { m->pipeline = static_cast<unsigned>(m->pending.size() - 1); m->outputSeen = true; }
m->pending.pop_front(); return 1;
#else
Q_UNUSED(f); Q_UNUSED(image); return -1;
#endif
}
call_video_caps CallVideoDecoder::capabilities() {
static call_video_caps caps{};
static std::once_flag once;
std::call_once(once, [] {
for (unsigned codec = 1; codec <= 2; ++codec) {
unsigned profiles = 0, hardwareProfiles = 0, pipeline = 0;
for (unsigned profile = 1; profile <= (codec == 1 ? 2u : 1u); ++profile) {
uint8_t bytes[8192]; int size = call_video_probe_key(codec, profile, bytes, sizeof(bytes));
if (size < 0) continue;
for (Backend backend : {Backend::HardwareOnly, Backend::SoftwareOnly}) {
CallVideoDecoder decoder(backend);
call_video_frame input{}; input.call_id = 1; input.flags = CALL_VIDEO_KEY;
input.data = bytes; input.size = input.length = size;
input.format = {1, 1280, 720, 30, 0, (uint8_t)codec, (uint8_t)(codec == 1 ? 31 : 93), 4000000, (uint8_t)profile};
unsigned sent = 0, received = 0; bool valid = true;
const int64_t start = call_video_playout_now_us();
while (valid && received < 4 && call_video_playout_now_us() - start < 1500000) {
if (sent < 4 && call_video_playout_now_us() - start >= sent * 33333ll) {
input.frame_id = sent + 1; input.pts_us = 1000000 + sent * 33333ll;
int result = decoder.submit(input); if (result < 0) valid = false; else if (result) ++sent;
}
call_video_frame output{}; QImage image;
int result = decoder.receive(output, image);
if (result < 0) valid = false;
else if (result) { valid = output.pts_us == 1000000 + received * 33333ll; ++received; }
if (sent == 4 && decoder.finish() < 0) valid = false;
if (valid && received < 4) QThread::usleep(1000);
}
valid = valid && received == 4;
DEBUG_INFO(DEBUG_CATEGORY_CALL, "video decoder probe codec=%u profile=%u backend=%d valid=%d inputs=%u outputs=%u pipeline=%u",
codec, profile, int(backend), valid, sent, received, decoder.pipelineFrames());
if (valid) {
profiles |= profile;
if (backend == Backend::HardwareOnly) { hardwareProfiles |= profile; pipeline = std::max(pipeline, decoder.pipelineFrames()); }
break;
}
}
}
#ifdef HAVE_FFMPEG
gpuPipeline[codec - 1].store(pipeline); gpuProfiles[codec - 1].store(hardwareProfiles);
#endif
if (profiles) caps.decode[codec - 1] = {1280, 720, 30, 1280 * 720 * 30, 4000000,
(uint8_t)profiles, (uint8_t)(codec == 1 ? 31 : 93)};
}
});
return caps;
}