CmvrControlStation/src/camerasnapshotdecoder.h

60 lines
2.8 KiB
C
Raw Normal View History

#pragma once
#include "cmvr/api/camera_command.pb.h"
#include <QImage>
#include <QString>
#include <cstring>
#include <limits>
inline QImage decodeCameraSnapshot(const cmvr::api::FrameData &frame, QString &error)
{
error.clear();
if (frame.data().size() > 64 * 1024 * 1024) {
error = QStringLiteral("RGB 图像数据超过 64 MiB");
return {};
}
const QString codec = QString::fromStdString(frame.codec()).trimmed().toLower();
const bool raw = codec.isEmpty() || codec == QStringLiteral("none");
if (!raw) {
const QImage image = QImage::fromData(
reinterpret_cast<const uchar *>(frame.data().data()),
static_cast<int>(qMin<size_t>(frame.data().size(), std::numeric_limits<int>::max())));
if (image.isNull()) error = QStringLiteral("不支持的抓图编码:%1").arg(codec);
return image;
}
const int channels = frame.type() == cmvr::api::FrameData::U8C1 ? 1 : 3;
const bool sixteen = frame.type() == cmvr::api::FrameData::U16C3;
const bool validSize = frame.width() > 0 && frame.height() > 0
&& frame.width() <= 16384 && frame.height() <= 16384;
const qint64 size = validSize
? qint64(frame.width()) * frame.height() * channels * (sixteen ? 2 : 1) : 0;
if (frame.width() <= 0 || frame.height() <= 0 || frame.width() > 16384 || frame.height() > 16384
|| (frame.type() != cmvr::api::FrameData::U8C1
&& frame.type() != cmvr::api::FrameData::U8C3 && !sixteen)
|| size > 64 * 1024 * 1024 || quint64(size) != frame.data().size()) {
error = QStringLiteral("RGB 图像数据无效:%1×%2,类型=%3,字节数=%4")
.arg(frame.width()).arg(frame.height()).arg(frame.type()).arg(qulonglong(frame.data().size()));
return {};
}
const auto *data = reinterpret_cast<const uchar *>(frame.data().data());
if (!sixteen) {
const QImage borrowed(data, frame.width(), frame.height(), frame.width() * channels,
channels == 1 ? QImage::Format_Grayscale8 : QImage::Format_RGB888);
return channels == 1 ? borrowed.copy() : borrowed.rgbSwapped();
}
QImage image(frame.width(), frame.height(), QImage::Format_RGB888);
if (image.isNull()) { error = QStringLiteral("RGB 图像内存分配失败"); return {}; }
// Server serializes native OpenCV BGR16. Map the full 16-bit range to display RGB8.
for (int y = 0; y < frame.height(); ++y) {
uchar *out = image.scanLine(y);
for (int x = 0; x < frame.width(); ++x) {
for (int c = 0; c < 3; ++c) {
quint16 value;
std::memcpy(&value, data + (qint64(y) * frame.width() * 3 + x * 3 + (2 - c)) * 2, 2);
out[x * 3 + c] = uchar(value >> 8);
}
}
}
return image;
}