KEY_MOTION_INFO problem
Hello, dear developers. I am currently working on receiving motion vectors from H264 encoders. I am working on Rockchip RK3588 board. My image input is 1280 x 1024. I am reading images using opencv and then encoding them using the codec.
The result I receive is very strange:
- Only half of the motion vectors are inserted. The other half is always zero.
- The values I see are very strange. I have mvy=32 after each second line.
Code I use to get the data:
// #include "codecs/codec_h264.hpp"
// #include "codecs/rk_mpp/rk_mpp_encoding_h264_cfg.hpp"
// #include "codecs/rk_mpp/rk_mpp_encoding_h265_cfg.hpp"
#include <boost/program_options.hpp>
#include <rockchip/mpp_rc_api.h>
#include <rockchip/rk_mpi.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <string>
static constexpr auto kDefaultQpMin{10};
static constexpr auto kDefaultQpIp{2};
static constexpr auto kDefaultQpInit{26};
static constexpr auto kDefaultQpMax{51};
static constexpr RK_U8 qp_init = kDefaultQpInit;
static constexpr RK_U8 qp_min = kDefaultQpMin;
static constexpr RK_U8 qp_max = kDefaultQpMax;
static constexpr RK_U8 qp_min_i = kDefaultQpMin;
static constexpr RK_U8 qp_max_i = kDefaultQpMax;
static constexpr RK_U8 qp_ip = kDefaultQpIp;
namespace po = boost::program_options;
namespace fs = std::filesystem;
template <class T>
inline constexpr T alignSide(T size, T alignment) {
return ((size) + (alignment)-1) & ~((alignment)-1);
}
template <class T>
inline constexpr T mppAlign(T size, T alignment = 16) {
return alignSide(size, alignment);
}
po::variables_map parseCommandLineOptions(int argc, const char* argv[]) {
po::options_description desc("Allowed options");
desc.add_options()("help,h", "Show help message");
// desc.add_options()("port,p", po::value<int>()->required(), "Port number");
desc.add_options()("verbose,v", "Enable verbose output");
desc.add_options()(
"input,i",
po::value<std::string>()->default_value("input"),
"Folder with images");
desc.add_options()(
"output,o",
po::value<std::string>()->default_value("output"),
"Folder for output");
desc.add_options()(
"gop",
po::value<int>()->default_value(30),
"GOP (keyframe interval)");
desc.add_options()(
"bitrate",
po::value<int>()->default_value(4'000'000),
"bitrate in bits");
desc.add_options()(
"csv",
"save to bin format (no option) or csv format (with option)");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("help")) {
std::cout << desc << "\n";
}
return vm;
}
std::vector<std::string> loadImageNames(fs::path image_folder_path) {
std::vector<std::string> filenames;
try {
for (const auto& entry : fs::directory_iterator(image_folder_path)) {
if (entry.is_regular_file()) {
filenames.push_back(entry.path().string());
}
}
std::sort(filenames.begin(), filenames.end());
} catch (const fs::filesystem_error& e) {
spdlog::error("Filesystem error: {}", e.what());
} catch (const std::exception& e) {
spdlog::error("Other error: {}", e.what());
}
return filenames;
}
std::string getOutputNameCsv(fs::path image_path, fs::path output_path) {
return output_path / fmt::format("{}.csv", image_path.stem().string());
}
std::string getOutputNameBin(fs::path image_path, fs::path output_path) {
return output_path / fmt::format("{}.bin", image_path.stem().string());
}
int main(int argc, const char* argv[]) {
const auto vm = parseCommandLineOptions(argc, argv);
if (vm.contains("help")) {
return 0;
}
if (vm.contains("verbose")) {
spdlog::set_level(spdlog::level::debug);
} else {
spdlog::set_level(spdlog::level::info);
}
const auto save_format_csv = vm.contains("csv");
const auto image_files = loadImageNames(vm["input"].as<std::string>());
fs::path output_folder = vm["output"].as<std::string>();
fs::create_directory(output_folder);
cv::Mat init_mat = cv::imread(image_files[0]);
const auto width = static_cast<RK_U32>(init_mat.cols);
const auto height = static_cast<RK_U32>(init_mat.rows);
auto hor_stride = mppAlign(width);
auto ver_stride = mppAlign(height);
auto frame_buffer_size = static_cast<size_t>(width * height * 3);
// RK_U32
int ret = 0;
MppCtx ctx = nullptr;
MppApi* mpi = nullptr;
MppEncCfg enc_cfg = nullptr;
MppBufferGroup frm_grp = nullptr;
// MppTask task_in = nullptr;
MppTask task_out = nullptr;
MppBuffer frm_buf = nullptr;
MppPacket pkt = nullptr;
MppFrame frame = nullptr;
MppBuffer md_info;
// MppPacket
// Initialize the MPP context
ret = mpp_create(&ctx, &mpi);
if (MPP_OK != ret) {
spdlog::critical("MPP CREATE ERROR {}", ret);
return ret;
}
// Init encoding mode
ret = mpp_init(ctx, MPP_CTX_ENC, MPP_VIDEO_CodingAVC);
if (MPP_OK != ret) {
spdlog::critical("MPP INIT ERROR {}", ret);
return ret;
}
ret = mpp_enc_cfg_init(&enc_cfg);
if (MPP_OK != ret) {
spdlog::critical("MPP CONFIG INIT ERROR {}", ret);
return ret;
}
mpp_enc_cfg_set_s32(enc_cfg, "codec:type", MPP_VIDEO_CodingAVC);
mpp_enc_cfg_set_s32(enc_cfg, "h264:profile", 66);
mpp_enc_cfg_set_s32(enc_cfg, "h264:level", 41);
mpp_enc_cfg_set_s32(enc_cfg, "h264:stream_type", 1);
mpp_enc_cfg_set_s32(enc_cfg, "prep:width", static_cast<RK_S32>(width));
mpp_enc_cfg_set_s32(enc_cfg, "prep:height", static_cast<RK_S32>(height));
mpp_enc_cfg_set_s32(enc_cfg, "prep:hor_stride", static_cast<RK_S32>(hor_stride));
mpp_enc_cfg_set_s32(enc_cfg, "prep:ver_stride", static_cast<RK_S32>(ver_stride));
mpp_enc_cfg_set_u32(enc_cfg, "prep:format", MPP_FMT_BGR888);
mpp_enc_cfg_set_s32(enc_cfg, "rc:fps_in_num", 30);
mpp_enc_cfg_set_s32(enc_cfg, "rc:fps_in_denorm", 1);
mpp_enc_cfg_set_s32(enc_cfg, "rc:fps_in_flex", 1);
mpp_enc_cfg_set_s32(enc_cfg, "rc:fps_out_num", 30);
mpp_enc_cfg_set_s32(enc_cfg, "rc:fps_out_denorm", 1);
mpp_enc_cfg_set_s32(enc_cfg, "rc:fps_out_flex", 1);
mpp_enc_cfg_set_s32(enc_cfg, "rc:bps_target", 4'000'000);
mpp_enc_cfg_set_s32(enc_cfg, "rc:bps_max", 17 * 4'000'000 / 16);
mpp_enc_cfg_set_s32(enc_cfg, "rc:bps_min", 15 * 4'000'000 / 16);
mpp_enc_cfg_set_u32(
enc_cfg,
"rc:drop_mode",
static_cast<RK_U32>(MPP_ENC_RC_DROP_FRM_DISABLED));
mpp_enc_cfg_set_u32(enc_cfg, "rc:drop_thd", 20);
mpp_enc_cfg_set_u32(enc_cfg, "rc:drop_gap", 1);
mpp_enc_cfg_set_s32(enc_cfg, "rc:gop", vm["gop"].as<int>());
mpp_enc_cfg_set_s32(enc_cfg, "rc:qp_init", static_cast<RK_S32>(qp_init));
mpp_enc_cfg_set_s32(enc_cfg, "rc:qp_min", static_cast<RK_S32>(qp_min));
mpp_enc_cfg_set_s32(enc_cfg, "rc:qp_max", static_cast<RK_S32>(qp_max));
mpp_enc_cfg_set_s32(enc_cfg, "rc:qp_min_i", static_cast<RK_S32>(qp_min_i));
mpp_enc_cfg_set_s32(enc_cfg, "rc:qp_max_i", static_cast<RK_S32>(qp_max_i));
mpp_enc_cfg_set_s32(enc_cfg, "rc:qp_ip", static_cast<RK_S32>(qp_ip));
// config.apply(enc_cfg);
ret = mpi->control(ctx, MPP_ENC_SET_CFG, enc_cfg);
if (MPP_OK != ret) {
spdlog::critical("MPP CONFIG APPLY ERROR {}", ret);
return ret;
}
// init frame
ret = mpp_buffer_group_get_internal(&frm_grp, MPP_BUFFER_TYPE_ION);
if (MPP_OK != ret) {
spdlog::critical("Failed to get buffer group {}", ret);
mpp_destroy(ctx);
return ret;
}
if (MPP_OK != mpp_buffer_get(frm_grp, &frm_buf, frame_buffer_size)) {
fprintf(stderr, "Failed to get buffer\n");
mpp_destroy(ctx);
return -1;
}
mpp_frame_init(&frame);
mpp_frame_set_width(frame, width);
mpp_frame_set_height(frame, height);
mpp_frame_set_hor_stride(frame, width);
mpp_frame_set_ver_stride(frame, height);
mpp_frame_set_fmt(frame, MPP_FMT_BGR888);
mpp_frame_set_buffer(frame, frm_buf);
spdlog::critical("sizeof = {}", sizeof(MppEncMDBlkInfo));
size_t ver_size = static_cast<size_t>(ver_stride / 16);
size_t hor_size = static_cast<size_t>(((hor_stride + 255) & (~255U)) / 16);
auto motion_size = 4 * hor_size * ver_size;
mpp_buffer_get(frm_grp, &md_info, motion_size);
for (const auto& image_file : image_files) {
spdlog::info("Processing {}", image_file);
auto input_frame = cv::imread(image_file);
if (input_frame.empty()) {
spdlog::critical("Failed to read frame {}", image_file);
return -1;
}
::memcpy(mpp_buffer_get_ptr(frm_buf), input_frame.data, frame_buffer_size);
MppTask task_in = nullptr;
ret = mpi->poll(ctx, MPP_PORT_INPUT, static_cast<MppPollType>(1000));
if (MPP_OK != ret) {
spdlog::error("Failed to pool input port {}", ret);
return ret;
}
ret = mpi->dequeue(ctx, MPP_PORT_INPUT, &task_in);
if (MPP_OK != ret) {
spdlog::error("Failed to dequeue task {}", ret);
return ret;
}
spdlog::debug("Setting frame to task");
mpp_task_meta_set_frame(task_in, KEY_INPUT_FRAME, frame);
mpp_task_meta_set_buffer(task_in, KEY_MOTION_INFO, md_info);
spdlog::debug("Enqueue task");
ret = mpi->enqueue(ctx, MPP_PORT_INPUT, task_in);
if (MPP_OK != ret) {
spdlog::error("Failed to enqueue task {}", ret);
return ret;
}
mpi->poll(ctx, MPP_PORT_OUTPUT, MPP_POLL_BLOCK);
mpi->dequeue(ctx, MPP_PORT_OUTPUT, &task_out);
spdlog::debug("Pooled task successfully");
ret = mpp_task_meta_get_packet(task_out, KEY_OUTPUT_PACKET, &pkt);
if (MPP_OK != ret) {
spdlog::error("Failed to get packet {}", ret);
return ret;
}
if (mpp_packet_has_meta(pkt)) {
MppMeta pkt_meta = nullptr;
MppBuffer motion = nullptr;
pkt_meta = mpp_packet_get_meta(pkt);
ret = mpp_meta_get_buffer(pkt_meta, KEY_MOTION_INFO, &motion);
if (MPP_OK != ret) {
spdlog::error("FAILED TO GET MOTION INFO META {}", ret);
} else {
auto* md_info_ptr =
static_cast<MppEncMDBlkInfo*>(mpp_buffer_get_ptr(motion));
std::string output_path;
if (save_format_csv) {
output_path = getOutputNameCsv(image_file, output_folder);
std::ofstream out(output_path);
out << fmt::format("row,col,sad,mvx,mvy\n");
for (size_t row = 0; row < ver_size;
++row, md_info_ptr += hor_size) {
for (size_t col = 0; col < hor_size; ++col) {
out << fmt::format(
"{},{},{},{},{}\n",
row,
col,
static_cast<RK_U32>(md_info_ptr[col].sad),
static_cast<RK_S32>(md_info_ptr[col].mvx),
static_cast<RK_S32>(md_info_ptr[col].mvy));
}
}
} else {
output_path = getOutputNameBin(image_file, output_folder);
std::ofstream out(output_path, std::ios::binary);
out.write(
reinterpret_cast<const char*>(md_info_ptr),
static_cast<std::streamsize>(motion_size));
}
spdlog::info("Saving to {}", output_path);
}
}
mpp_packet_deinit(&pkt);
ret = mpi->enqueue(ctx, MPP_PORT_OUTPUT, task_out);
if (MPP_OK != ret) {
spdlog::error("Failed to enqueue input {}", ret);
return ret;
}
}
return ret;
}
I am also attaching the result of csv to this issue.
Comment for rockchip-linux/mpp#825
中文
Hi, 我遇到了完全相同的问题。
平台: RK3588
输入: 752x480 grayscale (EuRoC MAV sequence)
编码: H.264 AVC
我也参考了 rk_venc_cmd.h 中的 MppEncMDBlkInfo 定义,按 32-bit / macroblock、raster order 去解析 motion data,但得到的结果非常异常:
- 大约只有一半的 macroblock 有非零 motion vector,另一半全为 0;
- 非零区域的数值看起来不像正常的 MV,sad 和 mvx/mvy 的分布极不规律。
我的 motion buffer 分配方式如下:
// hor_stride = MPP_ALIGN(width, 256) -> 768
// ver_stride = MPP_ALIGN(height, 16) -> 480
size_t hor_md = MPP_ALIGN(hor_stride, 256) / 16; // 48
size_t ver_md = ver_stride / 16; // 30
int mdinfo_size = hor_md * ver_md * sizeof(MppEncMDBlkInfo); // 5760
解析代码:
const MppEncMDBlkInfo *md = (const MppEncMDBlkInfo *)mpp_buffer_get_ptr(md_buf);
for (int row = 0; row < mb_rows; row++) {
for (int col = 0; col < mb_cols; col++) {
int md_idx = row * hor_md + col;
int out_idx = row * mb_cols + col;
decoded[out_idx].sad = md[md_idx].sad;
decoded[out_idx].mvx = md[md_idx].mvx;
decoded[out_idx].mvy = md[md_idx].mvy;
}
}
我注意到 mpi_enc_test.c 中有一个 get_mdinfo_size() 函数,对 RK3588 的计算公式和其他 SoC 不同:
// RK3588
md_size = (MPP_ALIGN(w, 64) >> 6) * (MPP_ALIGN(h, 64) >> 6) * 32;
// 其他 SoC (H264)
md_size = (MPP_ALIGN(w, 64) >> 6) * (MPP_ALIGN(h, 16) >> 4) * 16;
对于 768x480,RK3588 算出来只有 3072 bytes,而其他 SoC 是 5760 bytes。这意味着 RK3588 上每个 macroblock 可能只有 2 bytes(而不是 MppEncMDBlkInfo 的 4 bytes)。如果确实如此,buffer 中的 layout 应该不是简单的 raster-order MppEncMDBlkInfo。
请问官方能否确认 RK3588 上 motion data 的确切格式和解析方式?文档中并没有提到这种差异。
English
Hi, I'm experiencing the exact same issue.
Platform: RK3588
Input: 752x480 grayscale (EuRoC MAV sequence)
Codec: H.264 AVC
I also parse motion data according to the MppEncMDBlkInfo definition in rk_venc_cmd.h (32-bit per macroblock, raster order), but the results are completely off:
- Roughly half of the macroblocks have non-zero motion vectors while the other half are all zeros;
- The non-zero values don't look like valid MVs at all — the sad / mvx / mvy distributions are highly irregular.
My motion buffer allocation:
// hor_stride = MPP_ALIGN(width, 256) -> 768
// ver_stride = MPP_ALIGN(height, 16) -> 480
size_t hor_md = MPP_ALIGN(hor_stride, 256) / 16; // 48
size_t ver_md = ver_stride / 16; // 30
int mdinfo_size = hor_md * ver_md * sizeof(MppEncMDBlkInfo); // 5760
Parsing code:
const MppEncMDBlkInfo *md = (const MppEncMDBlkInfo *)mpp_buffer_get_ptr(md_buf);
for (int row = 0; row < mb_rows; row++) {
for (int col = 0; col < mb_cols; col++) {
int md_idx = row * hor_md + col;
int out_idx = row * mb_cols + col;
decoded[out_idx].sad = md[md_idx].sad;
decoded[out_idx].mvx = md[md_idx].mvx;
decoded[out_idx].mvy = md[md_idx].mvy;
}
}
I noticed that get_mdinfo_size() in mpi_enc_test.c uses a different formula for RK3588:
// RK3588
md_size = (MPP_ALIGN(w, 64) >> 6) * (MPP_ALIGN(h, 64) >> 6) * 32;
// Other SoCs (H264)
md_size = (MPP_ALIGN(w, 64) >> 6) * (MPP_ALIGN(h, 16) >> 4) * 16;
For 768x480, RK3588 gives only 3072 bytes, while other SoCs get 5760 bytes. This implies RK3588 may output only 2 bytes per macroblock instead of the 4 bytes defined by MppEncMDBlkInfo. If that's the case, the buffer layout is clearly not a simple raster-order MppEncMDBlkInfo array.
Could the maintainers please confirm the exact motion data format and parsing method for RK3588? The current documentation (rk_venc_cmd.h) does not mention this discrepancy at all.
3588 motion info排布格式如下,请参考:
(1)每 8 字节表示一个块的信息: HEVC:图像分辨率按 64x64 对齐,每 8 字节表示一个 32x32 块的信息,存储顺序按照 CTU 光栅序, CTU 内部按照 32x32 块光栅序; H.264:图像分辨率按 64x16 对齐,每 8 字节表示一个 64x16 块的信息,存储顺序按照 64x16 块的光栅序。 (2) 8 字节数据从高位到低位表示为 bit63~bit0,其中, cmv_x = bit[53:48], cmv_y = bit[59:55],bit54 和 bit60 为相应的符号位。结果为单像素精度。 (3) 1/4 像素精度 MV 为 mv_x = cmv_x * 4; mv_y = cmv_y * 4。
感谢回复。请问当前版本库代码中的MppEncMDBlkInfo_t适用于什么芯片呢