Compare commits

...

5 Commits

Author SHA1 Message Date
JohannesItten ee47d85cbd feat: exit node on NDI source format change
On status_change, probe() the new format and compare against the
format used to create the MXL flow. If resolution or fps changed,
throw with a descriptive message so the caller exits cleanly.

The existing catch in NDIInNode::run() logs the reason and breaks
out of the loop, causing the process to exit. Studio-manager detects
the exit and logs it — operator can restart to pick up the new format.

Same-format status changes (e.g. metadata only) still return false
and repeat the last frame as before.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:27:06 +03:00
JohannesItten 10d1282059 feat: fan-out ndiin video flow to both fakesink and ndiout
Share a single UUID across both edges so both readers connect to the
same MXL flow. MXL supports multiple readers per flow natively — each
reader has its own read pointer into the ring buffer.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:18:12 +03:00
JohannesItten e6d72ab431 fix: ndiout — RAII for NDI lifecycle, vectors instead of malloc
- NDIContext struct handles NDIlib_initialize/send_create/send_destroy/destroy
  so NDIlib_destroy() is guaranteed even if send_create fails (was leaked before)
- malloc/free for 10-bit and 16-bit frame buffers → std::vector<uint8_t>
- NDI frame structs point into vector data, no manual lifetime management
- static_cast for FourCC instead of C-style cast
- Tidy: ndi_frame_count replaces ndi_frame_counter, ++prefix form

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:15:44 +03:00
JohannesItten 12c87db4e2 refactor: NDIHelper → NDIReceiver with cleaner API and naming
NDIReceiver (shared/NDIReceiver.hpp):
- Rename class NDIHelper → NDIReceiver, file NDIHelper.hpp → NDIReceiver.hpp
- Add SourceInfo struct (width, height, fps_num, fps_den, stride, fourcc)
  replacing raw public member variables (xres, yres, frame_N, frame_D, stride)
- find_sources() now returns std::vector<std::string> instead of output pointer
- select_source() + get_source_info() → connect() + probe() (cleaner sequence,
  probe() returns SourceInfo and stores it internally for capture_v210)
- getV210_video_frame() → capture_v210() — removes unused source_num parameter
- get_bytes_per_pixel, fourCCtoStr → private static bytes_per_pixel, fourcc_str
- u_int32_t → uint32_t; (uint32_t) casts → static_cast
- probe() checks g_running to avoid hanging if source never sends video

ndiin/main.cpp:
- Update to new NDIReceiver API
- malloc/free latest_buffer → std::vector<uint8_t> latest_frame
- Remove unused #include <Processing.NDI.Lib.h> and V210.hpp
- memcpy uses latest_frame.size() instead of separate frame_bytes variable

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:13:36 +03:00
JohannesItten 7a32fa20af fix: NDI node correctness and robustness fixes
NDIHelper:
- find_sources: check g_running each attempt to avoid 50s block on shutdown
- getV210_video_frame: fix P216 branch (fall-through + local pointer reassignment bug)
- getV210_video_frame: status_change re-queries source info instead of throwing
- select_source: fix typo "recieve" → "receive"

ndiout:
- set frame_rate_N/frame_rate_D on the NDI send frame (was 0/0)
- add per-second stats logging (matching fakesink pattern)
- add missing <chrono> include
- fix typo "reciever" → "receiver"

ndiin:
- read source_num from NODE_CONFIG (key: "source_num", default 0)
- wrap hot-loop NDI call in try/catch so source-lost terminates cleanly
- pass source_num through to getV210_video_frame

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:07:45 +03:00
5 changed files with 319 additions and 289 deletions
+30 -30
View File
@@ -1,26 +1,25 @@
#include <cstring>
#include <string> #include <string>
#include <vector>
#include <mxl/flow.h> #include <mxl/flow.h>
#include <mxl/time.h> #include <mxl/time.h>
#include "NodeBase.hpp" #include "NodeBase.hpp"
#include "FlowDef.hpp" #include "FlowDef.hpp"
#include "V210.hpp" #include "NDIReceiver.hpp"
#include "NDIHelper.hpp"
#include <Processing.NDI.Lib.h>
#include <cstring>
class NDIInNode : public dmf::NodeBase { class NDIInNode : public dmf::NodeBase {
void run() override { void run() override {
dmf::NDIHelper ndi_helper; const auto source_num = static_cast<uint32_t>(config().value("source_num", 0));
dmf::NDIReceiver ndi;
dmf::NDIReceiver::SourceInfo src;
try { try {
std::vector<std::string> ndi_sources; auto sources = ndi.find_sources(5000);
ndi_helper.find_sources(&ndi_sources, 5000);
log("Available NDI sources:"); log("Available NDI sources:");
for (const auto& source_name : ndi_sources){ for (const auto& name : sources)
log("%s", source_name.c_str()); log(" %s", name.c_str());
} ndi.connect(source_num);
uint32_t source_num = 0; src = ndi.probe();
ndi_helper.select_source(source_num);
ndi_helper.get_source_info(source_num);
} catch (const std::runtime_error& e) { } catch (const std::runtime_error& e) {
log("Error: %s", e.what()); log("Error: %s", e.what());
return; return;
@@ -28,10 +27,10 @@ class NDIInNode : public dmf::NodeBase {
const auto flow_info = config().at("flow_id"); const auto flow_info = config().at("flow_id");
const auto flow_id = flow_info.at("id").get<std::string>(); const auto flow_id = flow_info.at("id").get<std::string>();
const int width = flow_info.value("width", ndi_helper.xres); const int width = flow_info.value("width", src.width);
const int height = flow_info.value("height", ndi_helper.yres); const int height = flow_info.value("height", src.height);
const int fps_num = flow_info.value("fps_num", ndi_helper.frame_N); const int fps_num = flow_info.value("fps_num", src.fps_num);
const int fps_den = flow_info.value("fps_den", ndi_helper.frame_D); const int fps_den = flow_info.value("fps_den", src.fps_den);
log("flow=%s %dx%d @ %d/%d fps", flow_id.c_str(), width, height, fps_num, fps_den); log("flow=%s %dx%d @ %d/%d fps", flow_id.c_str(), width, height, fps_num, fps_den);
@@ -57,18 +56,21 @@ class NDIInNode : public dmf::NodeBase {
uint64_t index = mxlGetCurrentIndex(&rate); uint64_t index = mxlGetCurrentIndex(&rate);
log("start index=%llu", index); log("start index=%llu", index);
// because NDI can drop to 1 FPS for static frames, even if source is 29.97p // NDI can drop to 1fps for static content — hold last valid frame
const size_t frame_bytes = stride * height; std::vector<uint8_t> latest_frame(stride * height);
uint8_t* latest_buffer = (uint8_t*)malloc(frame_bytes); bool have_frame = false;
bool last_ndi_frame_valid = false;
while (dmf::g_running.load(std::memory_order_relaxed)) { while (dmf::g_running.load(std::memory_order_relaxed)) {
if (ndi_helper.getV210_video_frame(0, latest_buffer, stride)) { try {
last_ndi_frame_valid = true; if (ndi.capture_v210(latest_frame.data(), stride))
have_frame = true;
} catch (const std::runtime_error& e) {
log("NDI error: %s — stopping", e.what());
break;
} }
uint8_t* buf = nullptr;
mxlGrainInfo grain{}; mxlGrainInfo grain{};
uint8_t* buf = nullptr;
st = mxlFlowWriterOpenGrain(writer, index, &grain, &buf); st = mxlFlowWriterOpenGrain(writer, index, &grain, &buf);
if (st != MXL_STATUS_OK) { if (st != MXL_STATUS_OK) {
@@ -77,14 +79,14 @@ class NDIInNode : public dmf::NodeBase {
continue; continue;
} }
if (last_ndi_frame_valid) { if (have_frame) {
std::memcpy(buf, latest_buffer, frame_bytes); std::memcpy(buf, latest_frame.data(), latest_frame.size());
grain.flags = 0; grain.flags = 0;
} else { } else {
grain.flags = MXL_GRAIN_FLAG_INVALID; grain.flags = MXL_GRAIN_FLAG_INVALID;
} }
grain.validSlices = grain.totalSlices; // mark grain complete so readers can consume it grain.validSlices = grain.totalSlices;
mxlFlowWriterCommitGrain(writer, &grain); mxlFlowWriterCommitGrain(writer, &grain);
const uint64_t ns = mxlGetNsUntilIndex(index + 1, &rate); const uint64_t ns = mxlGetNsUntilIndex(index + 1, &rate);
@@ -93,13 +95,11 @@ class NDIInNode : public dmf::NodeBase {
} }
log("stopped at index=%llu", index); log("stopped at index=%llu", index);
free(latest_buffer);
mxlReleaseFlowWriter(instance(), writer); mxlReleaseFlowWriter(instance(), writer);
} }
}; };
int main() int main() {
{
NDIInNode node; NDIInNode node;
return node.execute(); return node.execute();
} }
+70 -52
View File
@@ -1,4 +1,8 @@
#include <chrono>
#include <cstring>
#include <stdexcept>
#include <string> #include <string>
#include <vector>
#include <mxl/flow.h> #include <mxl/flow.h>
#include <mxl/time.h> #include <mxl/time.h>
#include "NodeBase.hpp" #include "NodeBase.hpp"
@@ -6,6 +10,29 @@
#include "V210.hpp" #include "V210.hpp"
#include <Processing.NDI.Lib.h> #include <Processing.NDI.Lib.h>
// RAII wrapper: init NDI, create sender, destroy both on scope exit.
struct NDIContext {
NDIlib_send_instance_t sender = nullptr;
explicit NDIContext(const char* ndi_name) {
if (!NDIlib_is_supported_CPU())
throw std::runtime_error("CPU not sufficient for NDI");
if (!NDIlib_initialize())
throw std::runtime_error("NDI lib init failed");
NDIlib_send_create_t desc{};
desc.p_ndi_name = ndi_name;
sender = NDIlib_send_create(&desc);
if (!sender) {
NDIlib_destroy();
throw std::runtime_error("Cannot create NDI send instance");
}
}
~NDIContext() {
NDIlib_send_destroy(sender);
NDIlib_destroy();
}
};
class NDIOutNode : public dmf::NodeBase { class NDIOutNode : public dmf::NodeBase {
void run() override { void run() override {
const auto flow_info = config().at("flow_id"); const auto flow_info = config().at("flow_id");
@@ -36,50 +63,36 @@ class NDIOutNode : public dmf::NodeBase {
mxlFlowReaderGetConfigInfo(reader, &cfg_info); mxlFlowReaderGetConfigInfo(reader, &cfg_info);
const uint32_t mxl_stride = cfg_info.discrete.sliceSizes[0]; const uint32_t mxl_stride = cfg_info.discrete.sliceSizes[0];
const mxlRational rate = {fps_num, fps_den}; NDIContext ndi(flow_id.c_str());
// V210 (10-bit) intermediate and P216 (16-bit) send buffers
std::vector<uint8_t> buf_10bit(mxl_stride * height);
std::vector<uint8_t> buf_16bit(width * sizeof(uint16_t) * 2 * height);
NDIlib_video_frame_v2_t ndi_frame_10bit{};
ndi_frame_10bit.xres = width;
ndi_frame_10bit.yres = height;
ndi_frame_10bit.FourCC = static_cast<NDIlib_FourCC_video_type_e>(NDI_LIB_FOURCC('V','2','1','0'));
ndi_frame_10bit.line_stride_in_bytes = mxl_stride;
ndi_frame_10bit.p_data = buf_10bit.data();
NDIlib_video_frame_v2_t ndi_frame_16bit{};
ndi_frame_16bit.xres = width;
ndi_frame_16bit.yres = height;
ndi_frame_16bit.frame_rate_N = fps_num;
ndi_frame_16bit.frame_rate_D = fps_den;
ndi_frame_16bit.line_stride_in_bytes = width * static_cast<int>(sizeof(uint16_t));
ndi_frame_16bit.p_data = buf_16bit.data();
const mxlRational rate = {fps_num, fps_den};
uint64_t index = mxlGetCurrentIndex(&rate); uint64_t index = mxlGetCurrentIndex(&rate);
uint64_t frame_count = 0; uint64_t frame_count = 0;
uint64_t invalid_count = 0; uint64_t invalid_count = 0;
uint64_t late_count = 0; uint64_t late_count = 0;
uint64_t ndi_frame_count = 0;
auto wall_start = std::chrono::steady_clock::now(); auto wall_start = std::chrono::steady_clock::now();
auto last_log_time = wall_start; auto last_log_time = wall_start;
// NDI part
if (!NDIlib_initialize()) {
// Cannot run NDI. Most likely because the CPU is not sufficient (see SDK documentation).
log("Cannot run NDI");
if (!NDIlib_is_supported_CPU()) {
log("CPU is not sufficient for NDI");
}
return;
}
NDIlib_send_create_t NDI_send_create_desc;
NDI_send_create_desc.p_ndi_name = flow_id.c_str();
NDIlib_send_instance_t pNDI_send = NDIlib_send_create(&NDI_send_create_desc);
if (!pNDI_send) {
log("Cannot create NDI send instance");
return;
}
NDIlib_video_frame_v2_t NDI_video_frame_10bit;
NDI_video_frame_10bit.xres = width;
NDI_video_frame_10bit.yres = height;
NDI_video_frame_10bit.FourCC = (NDIlib_FourCC_video_type_e)NDI_LIB_FOURCC('V', '2', '1', '0');
NDI_video_frame_10bit.line_stride_in_bytes = mxl_stride;
NDI_video_frame_10bit.p_data = (uint8_t*)malloc(NDI_video_frame_10bit.line_stride_in_bytes * NDI_video_frame_10bit.yres);
NDIlib_video_frame_v2_t NDI_video_frame_16bit;
NDI_video_frame_16bit.xres = NDI_video_frame_10bit.xres;
NDI_video_frame_16bit.yres = NDI_video_frame_10bit.yres;
NDI_video_frame_16bit.line_stride_in_bytes = NDI_video_frame_16bit.xres * sizeof(uint16_t);
NDI_video_frame_16bit.p_data = (uint8_t*)malloc(NDI_video_frame_16bit.line_stride_in_bytes * 2 * NDI_video_frame_16bit.yres);
//
uint64_t ndi_frame_counter = 0;
while (dmf::g_running.load(std::memory_order_relaxed)) { while (dmf::g_running.load(std::memory_order_relaxed)) {
mxlGrainInfo grain{}; mxlGrainInfo grain{};
uint8_t* buf = nullptr; uint8_t* buf = nullptr;
@@ -90,39 +103,44 @@ class NDIOutNode : public dmf::NodeBase {
frame_count++; frame_count++;
if (grain.flags & MXL_GRAIN_FLAG_INVALID) invalid_count++; if (grain.flags & MXL_GRAIN_FLAG_INVALID) invalid_count++;
index++; index++;
if (NDIlib_send_get_no_connections(pNDI_send,0) == 0) {
ndi_frame_counter = 0; if (NDIlib_send_get_no_connections(ndi.sender, 0) > 0) {
continue; std::memcpy(ndi_frame_10bit.p_data, buf, mxl_stride * height);
} NDIlib_util_V210_to_P216(&ndi_frame_10bit, &ndi_frame_16bit);
memcpy(NDI_video_frame_10bit.p_data, buf, mxl_stride * height); NDIlib_send_send_video_v2(ndi.sender, &ndi_frame_16bit);
NDIlib_util_V210_to_P216(&NDI_video_frame_10bit, &NDI_video_frame_16bit); if (++ndi_frame_count == 1)
NDIlib_send_send_video_v2(pNDI_send, &NDI_video_frame_16bit); log("NDI receiver connected");
ndi_frame_counter++; } else {
if (ndi_frame_counter == 1) { ndi_frame_count = 0;
log("NDI reciever got feed");
} }
} else if (st == MXL_ERR_OUT_OF_RANGE_TOO_EARLY) { } else if (st == MXL_ERR_OUT_OF_RANGE_TOO_EARLY) {
mxlSleepForNs(1'000'000); // 1 ms poll mxlSleepForNs(1'000'000);
} else if (st == MXL_ERR_OUT_OF_RANGE_TOO_LATE) { } else if (st == MXL_ERR_OUT_OF_RANGE_TOO_LATE) {
late_count++; late_count++;
// Jump to the most recent frame in the ring buffer
mxlFlowRuntimeInfo ri{}; mxlFlowRuntimeInfo ri{};
mxlFlowReaderGetRuntimeInfo(reader, &ri); mxlFlowReaderGetRuntimeInfo(reader, &ri);
index = ri.headIndex; index = ri.headIndex;
} else { } else {
log("unexpected status=%d on index=%llu", st, index); log("unexpected status=%d on index=%llu", st, index);
break; break;
} }
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration<double>(now - last_log_time).count() >= 1.0) {
const double elapsed = std::chrono::duration<double>(now - wall_start).count();
log("frames=%llu invalid=%llu late=%llu avg=%.2f fps",
frame_count, invalid_count, late_count,
static_cast<double>(frame_count) / elapsed);
last_log_time = now;
}
} }
log("stopped — total frames=%llu invalid=%llu late=%llu", log("stopped — total frames=%llu invalid=%llu late=%llu",
frame_count, invalid_count, late_count); frame_count, invalid_count, late_count);
mxlReleaseFlowReader(instance(), reader); mxlReleaseFlowReader(instance(), reader);
free(NDI_video_frame_10bit.p_data);
free(NDI_video_frame_16bit.p_data);
NDIlib_send_destroy(pNDI_send);
NDIlib_destroy();
} }
}; };
-194
View File
@@ -1,194 +0,0 @@
#include <stdexcept>
#include <vector>
#include <string>
#include <Processing.NDI.Lib.h>
#include "V210.hpp"
namespace dmf {
class NDIHelper {
public:
int xres = 0, yres = 0, frame_D = 0, frame_N = 0, stride = 0;
NDIHelper() {
if (!NDIlib_is_supported_CPU()) {
throw std::runtime_error("CPU is not sufficient for NDI");
}
if (!NDIlib_initialize()) {
throw std::runtime_error("NDI lib init failed");
}
}
~NDIHelper() {
if (pNDI_recv) NDIlib_recv_destroy(pNDI_recv);
if (pNDI_find) NDIlib_find_destroy(pNDI_find);
NDIlib_destroy();
}
void find_sources(std::vector<std::string>* sources, u_int32_t timeout_ms) {
pNDI_find = NDIlib_find_create_v2();
if (!pNDI_find) {
throw std::runtime_error("Cannot create NDI finder");
}
const int max_attempts = 10;
uint32_t sources_amount = 0;
const NDIlib_source_t* p_sources = nullptr;
for (int attempt = 0; !sources_amount && attempt < max_attempts; ++attempt) {
NDIlib_find_wait_for_sources(pNDI_find, timeout_ms);
p_sources = NDIlib_find_get_current_sources(pNDI_find, &sources_amount);
}
if (!sources_amount) {
NDIlib_find_destroy(pNDI_find);
pNDI_find = nullptr;
throw std::runtime_error("No NDI sources found after timeout");
}
// Copy while finder is alive: p_sources points into finder-owned memory
for (uint32_t i = 0; i < sources_amount; ++i) {
sources->push_back(p_sources[i].p_ndi_name);
cached_names.emplace_back(p_sources[i].p_ndi_name);
cached_urls.emplace_back(p_sources[i].p_url_address);
}
cached_sources.reserve(cached_names.size());
for (uint32_t i = 0; i < cached_names.size(); ++i) {
cached_sources.push_back({cached_names[i].c_str(), cached_urls[i].c_str()});
}
NDIlib_find_destroy(pNDI_find);
pNDI_find = nullptr;
}
void select_source(uint32_t source_num) {
if (cached_sources.empty()) {
throw std::runtime_error("0 sources found");
} else if (source_num >= cached_sources.size()) {
throw std::runtime_error("Source_num bigger that sources amount");
}
pNDI_recv = NDIlib_recv_create_v3();
if (!pNDI_recv) {
throw std::runtime_error("Cannot create NDI recieve instance");
}
NDIlib_recv_connect(pNDI_recv, &cached_sources[source_num]);
}
void get_source_info(uint32_t source_num) {
NDIlib_video_frame_v2_t video_frame;
NDIlib_frame_type_e frame_type;
bool is_got_info = false;
while(!is_got_info)
{
frame_type = NDIlib_recv_capture_v3(pNDI_recv, &video_frame, nullptr, nullptr, 1000);
switch(frame_type)
{
case NDIlib_frame_type_video:
is_got_info = true;
xres = video_frame.xres;
yres = video_frame.yres;
frame_D = video_frame.frame_rate_D;
frame_N = video_frame.frame_rate_N;
fourCC = video_frame.FourCC;
stride = video_frame.line_stride_in_bytes;
if (stride == 0) {
stride = xres * get_bytes_per_pixel(fourCC);
}
break;
case NDIlib_frame_type_error:
is_got_info = true;
throw std::runtime_error("Selected NDI source is lost");
break;
}
}
NDIlib_recv_free_video_v2(pNDI_recv, &video_frame);
}
int get_bytes_per_pixel(NDIlib_FourCC_video_type_e fourCC) {
switch (fourCC) {
case NDIlib_FourCC_video_type_UYVY: // Standard 8-bit YUV 4:2:2
case NDIlib_FourCC_video_type_YV12: // 8-bit YUV 4:2:0
case NDIlib_FourCC_video_type_I420: // 8-bit YUV 4:2:0
case NDIlib_FourCC_video_type_NV12: // 8-bit YUV 4:2:0
// These are 4:2:2 or 4:2:0 formats.
// On average, they use 2 bytes (16 bits) per pixel across the macroblock.
return 2;
case NDIlib_FourCC_video_type_BGRA: // 8-bit RGB with Alpha
case NDIlib_FourCC_video_type_RGBA: // 8-bit RGB with Alpha
// 4 channels (Red, Green, Blue, Alpha) * 1 byte each
return 4;
case NDIlib_FourCC_video_type_BGRX: // 8-bit RGB (Padding)
case NDIlib_FourCC_video_type_RGBX: // 8-bit RGB (Padding)
// 4 channels (Red, Green, Blue, Empty) * 1 byte each
return 4;
case NDIlib_FourCC_video_type_UYVA: // 8-bit YUV 4:2:2 + Alpha channel
// 2 bytes for YUV + 1 byte for Alpha split
return 3;
case NDIlib_FourCC_video_type_P216: // 16-bit YUV 4:2:2 (High bit depth)
// 2 channels packed at 2 bytes (16-bits) per sample = 4 bytes per pixel
return 4;
case NDIlib_FourCC_video_type_PA16: // 16-bit YUV 4:2:2 + 16-bit Alpha
return 6;
default:
return 2; // Safe NDI default fallback
}
}
std::string fourCCtoStr() {
char fourcc_str[5];
uint32_t fourcc = (uint32_t)fourCC;
fourcc_str[0] = (fourcc >> 0) & 0xFF;
fourcc_str[1] = (fourcc >> 8) & 0xFF;
fourcc_str[2] = (fourcc >> 16) & 0xFF;
fourcc_str[3] = (fourcc >> 24) & 0xFF;
fourcc_str[4] = '\0';
return std::string(fourcc_str);
}
bool getV210_video_frame(uint32_t source_num, uint8_t* frame_buffer, uint32_t frame_stride) {
NDIlib_video_frame_v2_t video_frame;
NDIlib_frame_type_e frame_type;
frame_type = NDIlib_recv_capture_v3(pNDI_recv, &video_frame, nullptr, nullptr, 5);
switch(frame_type)
{
case NDIlib_frame_type_error:
throw std::runtime_error("NDI source lost");
case NDIlib_frame_type_status_change:
throw std::runtime_error("NDI source resolution or framerate are changed");
}
if (frame_type != NDIlib_frame_type_video) {
return false;
}
switch(fourCC)
{
case NDIlib_FourCC_type_UYVY:
v210::UYVYtoV210(video_frame.p_data, frame_buffer, xres, yres, stride, frame_stride);
break;
case NDIlib_FourCC_type_P216:
NDIlib_video_frame_v2_t video_frame_10bit;
NDIlib_util_P216_to_V210(&video_frame, &video_frame_10bit);
frame_buffer = video_frame.p_data;
default:
throw std::runtime_error("Color format is not supported yet");
}
NDIlib_recv_free_video_v2(pNDI_recv, &video_frame);
return true;
}
private:
// receive
NDIlib_find_instance_t pNDI_find = nullptr;
NDIlib_recv_instance_t pNDI_recv = nullptr;
NDIlib_FourCC_type_e fourCC;
// owned copies so finder can be destroyed early
std::vector<std::string> cached_names;
std::vector<std::string> cached_urls;
std::vector<NDIlib_source_t> cached_sources;
};
}
+202
View File
@@ -0,0 +1,202 @@
#pragma once
#include <stdexcept>
#include <string>
#include <vector>
#include <Processing.NDI.Lib.h>
#include "Signal.hpp"
#include "V210.hpp"
namespace dmf {
class NDIReceiver {
public:
struct SourceInfo {
int width = 0;
int height = 0;
int fps_num = 0;
int fps_den = 0;
int stride = 0;
NDIlib_FourCC_type_e fourcc{};
};
NDIReceiver() {
if (!NDIlib_is_supported_CPU())
throw std::runtime_error("CPU is not sufficient for NDI");
if (!NDIlib_initialize())
throw std::runtime_error("NDI lib init failed");
}
~NDIReceiver() {
if (recv_) NDIlib_recv_destroy(recv_);
if (find_) NDIlib_find_destroy(find_);
NDIlib_destroy();
}
// Discovers NDI sources on the network. Polls up to max_attempts times,
// each waiting timeout_ms milliseconds. Respects g_running.
std::vector<std::string> find_sources(uint32_t timeout_ms, int max_attempts = 10) {
find_ = NDIlib_find_create_v2();
if (!find_)
throw std::runtime_error("Cannot create NDI finder");
uint32_t count = 0;
const NDIlib_source_t* p_sources = nullptr;
for (int i = 0; !count && i < max_attempts; ++i) {
if (!dmf::g_running.load(std::memory_order_relaxed)) {
NDIlib_find_destroy(find_);
find_ = nullptr;
throw std::runtime_error("Interrupted while searching for NDI sources");
}
NDIlib_find_wait_for_sources(find_, timeout_ms);
p_sources = NDIlib_find_get_current_sources(find_, &count);
}
if (!count) {
NDIlib_find_destroy(find_);
find_ = nullptr;
throw std::runtime_error("No NDI sources found after timeout");
}
// Copy while finder is alive: p_sources points into finder-owned memory
std::vector<std::string> names;
for (uint32_t i = 0; i < count; ++i) {
names.emplace_back(p_sources[i].p_ndi_name);
source_names_.emplace_back(p_sources[i].p_ndi_name);
source_urls_.emplace_back(p_sources[i].p_url_address);
}
sources_.reserve(source_names_.size());
for (size_t i = 0; i < source_names_.size(); ++i)
sources_.push_back({source_names_[i].c_str(), source_urls_[i].c_str()});
NDIlib_find_destroy(find_);
find_ = nullptr;
return names;
}
// Connects to a discovered source by index.
void connect(uint32_t source_num) {
if (sources_.empty())
throw std::runtime_error("No sources available — call find_sources() first");
if (source_num >= static_cast<uint32_t>(sources_.size()))
throw std::runtime_error("source_num exceeds available source count");
recv_ = NDIlib_recv_create_v3();
if (!recv_)
throw std::runtime_error("Cannot create NDI receive instance");
NDIlib_recv_connect(recv_, &sources_[source_num]);
}
// Captures the first video frame to determine resolution, frame rate, and format.
// Stores the result internally for use by capture_v210(). Respects g_running.
SourceInfo probe() {
while (dmf::g_running.load(std::memory_order_relaxed)) {
NDIlib_video_frame_v2_t frame;
auto type = NDIlib_recv_capture_v3(recv_, &frame, nullptr, nullptr, 1000);
if (type == NDIlib_frame_type_error)
throw std::runtime_error("NDI source lost during probe");
if (type != NDIlib_frame_type_video)
continue;
info_.width = frame.xres;
info_.height = frame.yres;
info_.fps_num = frame.frame_rate_N;
info_.fps_den = frame.frame_rate_D;
info_.fourcc = static_cast<NDIlib_FourCC_type_e>(frame.FourCC);
info_.stride = frame.line_stride_in_bytes;
if (info_.stride == 0)
info_.stride = info_.width * bytes_per_pixel(info_.fourcc);
NDIlib_recv_free_video_v2(recv_, &frame);
return info_;
}
throw std::runtime_error("Interrupted during probe");
}
// Captures one video frame and converts it to V210 in frame_buffer.
// Returns false if no frame was available this tick (caller should repeat last frame).
// Throws on source lost or unsupported format.
bool capture_v210(uint8_t* frame_buffer, uint32_t frame_stride) {
NDIlib_video_frame_v2_t frame;
auto type = NDIlib_recv_capture_v3(recv_, &frame, nullptr, nullptr, 5);
if (type == NDIlib_frame_type_error)
throw std::runtime_error("NDI source lost");
if (type == NDIlib_frame_type_status_change) {
const SourceInfo old = info_;
info_ = probe();
if (info_.width != old.width || info_.height != old.height ||
info_.fps_num != old.fps_num || info_.fps_den != old.fps_den) {
throw std::runtime_error(
"source format changed: " +
std::to_string(old.width) + "x" + std::to_string(old.height) +
" @" + std::to_string(old.fps_num) + "/" + std::to_string(old.fps_den) +
" -> " +
std::to_string(info_.width) + "x" + std::to_string(info_.height) +
" @" + std::to_string(info_.fps_num) + "/" + std::to_string(info_.fps_den));
}
return false;
}
if (type != NDIlib_frame_type_video)
return false;
switch (info_.fourcc) {
case NDIlib_FourCC_type_UYVY:
v210::UYVYtoV210(frame.p_data, frame_buffer,
info_.width, info_.height, info_.stride, frame_stride);
break;
case NDIlib_FourCC_type_P216: {
NDIlib_video_frame_v2_t dst{};
dst.p_data = frame_buffer;
dst.line_stride_in_bytes = frame_stride;
NDIlib_util_P216_to_V210(&frame, &dst);
break;
}
default:
NDIlib_recv_free_video_v2(recv_, &frame);
throw std::runtime_error("Unsupported NDI color format: " + fourcc_str(info_.fourcc));
}
NDIlib_recv_free_video_v2(recv_, &frame);
return true;
}
private:
NDIlib_find_instance_t find_ = nullptr;
NDIlib_recv_instance_t recv_ = nullptr;
SourceInfo info_;
std::vector<std::string> source_names_;
std::vector<std::string> source_urls_;
std::vector<NDIlib_source_t> sources_;
static int bytes_per_pixel(NDIlib_FourCC_type_e fc) {
switch (fc) {
case NDIlib_FourCC_video_type_UYVY:
case NDIlib_FourCC_video_type_YV12:
case NDIlib_FourCC_video_type_I420:
case NDIlib_FourCC_video_type_NV12: return 2;
case NDIlib_FourCC_video_type_BGRA:
case NDIlib_FourCC_video_type_RGBA:
case NDIlib_FourCC_video_type_BGRX:
case NDIlib_FourCC_video_type_RGBX: return 4;
case NDIlib_FourCC_video_type_UYVA: return 3;
case NDIlib_FourCC_video_type_P216: return 4;
case NDIlib_FourCC_video_type_PA16: return 6;
default: return 2;
}
}
static std::string fourcc_str(NDIlib_FourCC_type_e fc) {
uint32_t v = static_cast<uint32_t>(fc);
char s[5] = {
static_cast<char>((v >> 0) & 0xFF),
static_cast<char>((v >> 8) & 0xFF),
static_cast<char>((v >> 16) & 0xFF),
static_cast<char>((v >> 24) & 0xFF),
'\0'
};
return s;
}
};
} // namespace dmf
+5 -1
View File
@@ -38,12 +38,16 @@ static std::string gen_uuid() {
static dmf::FlowGraph build_graph() { static dmf::FlowGraph build_graph() {
dmf::FlowGraph g; dmf::FlowGraph g;
const std::string video_flow = gen_uuid();
g.nodes = { g.nodes = {
{ "ndiin", "ndiin", {} }, { "ndiin", "ndiin", {} },
{ "fakesink", "fakesink", {} }, { "fakesink", "fakesink", {} },
{ "ndiout", "ndiout", {} },
}; };
g.edges = { g.edges = {
{ gen_uuid(), "ndiin", "flow_id", "fakesink", "flow_id", { video_flow, "ndiin", "flow_id", "fakesink", "flow_id",
{ {"kind","video"}, {"width",1920}, {"height",1080}, {"fps_num",25}, {"fps_den",1} } },
{ video_flow, "ndiin", "flow_id", "ndiout", "flow_id",
{ {"kind","video"}, {"width",1920}, {"height",1080}, {"fps_num",25}, {"fps_den",1} } }, { {"kind","video"}, {"width",1920}, {"height",1080}, {"fps_num",25}, {"fps_den",1} } },
}; };
return g; return g;