307 lines
16 KiB
C++
307 lines
16 KiB
C++
|
|
#include "../src/preview_capture.hpp"
|
||
|
|
#include <algorithm>
|
||
|
|
#include <array>
|
||
|
|
#include <climits>
|
||
|
|
#include <future>
|
||
|
|
#include <iostream>
|
||
|
|
#include <type_traits>
|
||
|
|
|
||
|
|
// OFFLINE ONLY: exercise the production buffer/row conversion helpers with
|
||
|
|
// synthetic BGRA pixels. No WorkerService, SDK DLL, HTTP listener or device.
|
||
|
|
using freescan::Json;
|
||
|
|
using freescan::detail::PreviewCallbackDiagnostics;
|
||
|
|
using freescan::detail::PreviewFramePool;
|
||
|
|
using freescan::detail::PreviewRawFrame;
|
||
|
|
using freescan::detail::flip_preview_rows;
|
||
|
|
namespace {
|
||
|
|
size_t passed = 0;
|
||
|
|
void check(bool condition, const std::string &message) {
|
||
|
|
if (!condition)
|
||
|
|
throw std::runtime_error(message);
|
||
|
|
++passed;
|
||
|
|
}
|
||
|
|
template <class F> void invalid(F operation, const std::string &message) {
|
||
|
|
try {
|
||
|
|
operation();
|
||
|
|
} catch (const std::invalid_argument &) {
|
||
|
|
check(true, message);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
throw std::runtime_error(message);
|
||
|
|
}
|
||
|
|
uint64_t count(const Json &value, const char *name) { return value.at(name).get<uint64_t>(); }
|
||
|
|
void no_vendor_dll() {
|
||
|
|
check(GetModuleHandleW(L"SDKCWrapper.dll") == nullptr, "Offline pool test must not load the SDK DLL.");
|
||
|
|
check(GetModuleHandleW(L"FreeScanNativeBridge.dll") == nullptr,
|
||
|
|
"Offline pool test must not load the scene bridge DLL.");
|
||
|
|
}
|
||
|
|
void capacity_and_ownership() {
|
||
|
|
static_assert(!std::is_copy_constructible_v<PreviewFramePool::Lease>);
|
||
|
|
static_assert(!std::is_copy_assignable_v<PreviewFramePool::Lease>);
|
||
|
|
static_assert(std::is_nothrow_move_constructible_v<PreviewFramePool::Lease>);
|
||
|
|
static_assert(std::is_nothrow_move_assignable_v<PreviewFramePool::Lease>);
|
||
|
|
PreviewFramePool pool;
|
||
|
|
auto initial = pool.snapshot();
|
||
|
|
check(count(initial, "capacity") == 3 && count(initial, "allocatedSlots") == 0 &&
|
||
|
|
count(initial, "inUse") == 0 && count(initial, "capacityBytes") == 0,
|
||
|
|
"A new pool is bounded to three slots without allocating pixel storage.");
|
||
|
|
std::array<PreviewFramePool::Lease, PreviewFramePool::capacity> leases;
|
||
|
|
for (auto &lease : leases) {
|
||
|
|
lease = pool.try_acquire();
|
||
|
|
check(bool(lease), "Each of the three unclaimed slots is available.");
|
||
|
|
pool.prepare(lease, 16, 8);
|
||
|
|
}
|
||
|
|
check(leases[0].get() != leases[1].get() && leases[0].get() != leases[2].get() &&
|
||
|
|
leases[1].get() != leases[2].get(),
|
||
|
|
"Three simultaneous leases have three distinct frame owners.");
|
||
|
|
std::fill(leases[0]->pixels.begin(), leases[0]->pixels.end(), uint8_t(73));
|
||
|
|
auto *encodingFrame = leases[0].get();
|
||
|
|
auto attempt = std::async(std::launch::async, [&pool] { return bool(pool.try_acquire()); });
|
||
|
|
const auto prompt = attempt.wait_for(std::chrono::seconds(1)) == std::future_status::ready;
|
||
|
|
// Release before reporting failure so a regression cannot deadlock cleanup.
|
||
|
|
if (!prompt)
|
||
|
|
for (auto &lease : leases)
|
||
|
|
lease.reset();
|
||
|
|
const bool fourthSucceeded = attempt.get();
|
||
|
|
check(prompt && !fourthSucceeded, "Pool exhaustion returns without waiting for an encoder-held slot.");
|
||
|
|
check(count(pool.snapshot(), "inUse") == 3 && count(pool.snapshot(), "peakInUse") == 3 &&
|
||
|
|
count(pool.snapshot(), "exhausted") >= 1,
|
||
|
|
"Exhaustion preserves every existing lease and records the bounded occupancy.");
|
||
|
|
auto *releasedFrame = leases[1].get();
|
||
|
|
leases[1].reset();
|
||
|
|
auto replacement = pool.try_acquire();
|
||
|
|
check(replacement.get() == releasedFrame && replacement.get() != encodingFrame,
|
||
|
|
"Only the released slot can be reused while the encoder retains its frame.");
|
||
|
|
std::fill(replacement->pixels.begin(), replacement->pixels.end(), uint8_t(191));
|
||
|
|
check(std::all_of(encodingFrame->pixels.begin(), encodingFrame->pixels.end(),
|
||
|
|
[](uint8_t pixel) { return pixel == 73; }),
|
||
|
|
"Writing a newly leased producer slot cannot overwrite an encoder-owned frame.");
|
||
|
|
auto moved = std::move(replacement);
|
||
|
|
check(!replacement && moved.get() == releasedFrame && count(pool.snapshot(), "inUse") == 3,
|
||
|
|
"Moving a lease transfers ownership without claiming another slot.");
|
||
|
|
moved = std::move(leases[2]);
|
||
|
|
check(!leases[2] && moved && count(pool.snapshot(), "inUse") == 2,
|
||
|
|
"Move assignment releases the former destination slot exactly once.");
|
||
|
|
moved.reset();
|
||
|
|
moved.reset();
|
||
|
|
leases[0].reset();
|
||
|
|
check(count(pool.snapshot(), "inUse") == 0,
|
||
|
|
"Reset is idempotent and every lease returns its slot after ownership transfers.");
|
||
|
|
{
|
||
|
|
auto automatic = pool.try_acquire();
|
||
|
|
check(automatic && count(pool.snapshot(), "inUse") == 1, "A released pool remains usable.");
|
||
|
|
}
|
||
|
|
check(count(pool.snapshot(), "inUse") == 0, "Lease destruction returns a slot without explicit cleanup.");
|
||
|
|
}
|
||
|
|
void reuse_and_dimensions() {
|
||
|
|
PreviewFramePool pool;
|
||
|
|
std::array<PreviewFramePool::Lease, PreviewFramePool::capacity> leases;
|
||
|
|
std::array<uint8_t *, PreviewFramePool::capacity> storage{};
|
||
|
|
uint64_t totalCapacity = 0;
|
||
|
|
for (size_t slot = 0; slot < leases.size(); ++slot) {
|
||
|
|
leases[slot] = pool.try_acquire();
|
||
|
|
pool.prepare(leases[slot], 32, 24);
|
||
|
|
storage[slot] = leases[slot]->pixels.data();
|
||
|
|
totalCapacity += leases[slot]->pixels.capacity();
|
||
|
|
}
|
||
|
|
const auto warmed = pool.snapshot();
|
||
|
|
check(count(warmed, "allocatedSlots") == 3 && count(warmed, "allocations") == 3 &&
|
||
|
|
count(warmed, "capacityBytes") == totalCapacity,
|
||
|
|
"Warmup allocates pixel storage once for each of the three slots.");
|
||
|
|
for (size_t slot = 0; slot < leases.size(); ++slot) {
|
||
|
|
for (int iteration = 0; iteration < 40; ++iteration)
|
||
|
|
pool.prepare(leases[slot], 32, 24);
|
||
|
|
check(leases[slot]->pixels.data() == storage[slot] && leases[slot]->pixels.size() == 32 * 24 * 4,
|
||
|
|
"Repeated same-resolution callbacks preserve the warmed pixel allocation.");
|
||
|
|
pool.prepare(leases[slot], 8, 8);
|
||
|
|
check(leases[slot]->pixels.data() == storage[slot] && leases[slot]->pixels.size() == 8 * 8 * 4,
|
||
|
|
"A smaller frame changes logical size without discarding reusable capacity.");
|
||
|
|
leases[slot].reset();
|
||
|
|
}
|
||
|
|
auto reused = pool.try_acquire();
|
||
|
|
pool.prepare(reused, 32, 24);
|
||
|
|
const auto repeated = pool.snapshot();
|
||
|
|
check(reused->pixels.data() == storage[0] && count(repeated, "allocations") == 3 &&
|
||
|
|
count(repeated, "capacityBytes") == totalCapacity && count(repeated, "reuses") >= 124,
|
||
|
|
"Returning and reacquiring a warmed slot does not allocate another frame buffer.");
|
||
|
|
auto *original = reused->pixels.data();
|
||
|
|
const auto oldSize = reused->pixels.size();
|
||
|
|
for (const auto dimensions : std::array<std::pair<int, int>, 10>{
|
||
|
|
{{0, 1}, {1, 0}, {-1, 1}, {1, -1}, {16385, 1}, {1, 16385},
|
||
|
|
{16384, 4097}, {4097, 16384}, {INT_MAX, 1}, {1, INT_MAX}}}) {
|
||
|
|
invalid([&] { pool.prepare(reused, dimensions.first, dimensions.second); },
|
||
|
|
"Invalid dimensions or an oversized BGRA request must be rejected before allocation.");
|
||
|
|
check(reused->pixels.data() == original && reused->pixels.size() == oldSize &&
|
||
|
|
reused->w == 32 && reused->h == 24,
|
||
|
|
"Rejecting a malformed frame preserves the last valid buffer and dimensions.");
|
||
|
|
}
|
||
|
|
PreviewFramePool::Lease empty;
|
||
|
|
invalid([&] { pool.prepare(empty, 1, 1); }, "An empty lease cannot prepare a frame.");
|
||
|
|
PreviewFramePool other;
|
||
|
|
auto foreign = other.try_acquire();
|
||
|
|
invalid([&] { pool.prepare(foreign, 1, 1); }, "A lease from another pool cannot prepare this pool's slot.");
|
||
|
|
pool.prepare(reused, 16384, 1);
|
||
|
|
check(reused->w == 16384 && reused->h == 1 && reused->pixels.size() == 65536,
|
||
|
|
"The documented width boundary is accepted without a large image allocation.");
|
||
|
|
pool.prepare(reused, 1, 16384);
|
||
|
|
check(reused->w == 1 && reused->h == 16384 && reused->pixels.size() == 65536,
|
||
|
|
"The documented height boundary is accepted without a large image allocation.");
|
||
|
|
pool.prepare(reused, 1, 1);
|
||
|
|
check(reused->pixels.size() == 4, "A one-pixel BGRA frame remains valid after resolution changes.");
|
||
|
|
}
|
||
|
|
void row_orientation() {
|
||
|
|
for (const auto dimensions : std::array<std::pair<int, int>, 5>{
|
||
|
|
{{1, 1}, {1, 2}, {2, 3}, {3, 4}, {7, 5}}}) {
|
||
|
|
PreviewRawFrame frame;
|
||
|
|
frame.w = dimensions.first;
|
||
|
|
frame.h = dimensions.second;
|
||
|
|
frame.epoch = 29;
|
||
|
|
frame.captured = 1234567;
|
||
|
|
frame.pixels.resize(size_t(frame.w) * frame.h * 4);
|
||
|
|
for (int y = 0; y < frame.h; ++y)
|
||
|
|
for (int x = 0; x < frame.w; ++x)
|
||
|
|
for (int channel = 0; channel < 4; ++channel)
|
||
|
|
frame.pixels[(size_t(y) * frame.w + x) * 4 + channel] =
|
||
|
|
uint8_t(y * 41 + x * 7 + channel);
|
||
|
|
const auto bottomUp = frame.pixels;
|
||
|
|
flip_preview_rows(frame);
|
||
|
|
bool correct = true;
|
||
|
|
const size_t row = size_t(frame.w) * 4;
|
||
|
|
for (int y = 0; y < frame.h; ++y)
|
||
|
|
correct = correct && std::equal(frame.pixels.begin() + size_t(y) * row,
|
||
|
|
frame.pixels.begin() + size_t(y + 1) * row,
|
||
|
|
bottomUp.begin() + size_t(frame.h - 1 - y) * row);
|
||
|
|
check(correct, "Encoder-side row conversion preserves every BGRA channel and corrects bottom-up orientation.");
|
||
|
|
check(frame.w == dimensions.first && frame.h == dimensions.second && frame.epoch == 29 &&
|
||
|
|
frame.captured == 1234567,
|
||
|
|
"Row conversion cannot change source dimensions, epoch or capture timestamp.");
|
||
|
|
if (frame.h % 2) {
|
||
|
|
const size_t middle = size_t(frame.h / 2) * row;
|
||
|
|
check(std::equal(frame.pixels.begin() + middle, frame.pixels.begin() + middle + row,
|
||
|
|
bottomUp.begin() + middle),
|
||
|
|
"An odd-height image retains its middle row exactly.");
|
||
|
|
}
|
||
|
|
flip_preview_rows(frame);
|
||
|
|
check(frame.pixels == bottomUp, "Two row flips recover the complete original synthetic frame.");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
void concurrent_producers_and_encoder() {
|
||
|
|
PreviewFramePool pool;
|
||
|
|
std::array<PreviewFramePool::Lease, PreviewFramePool::capacity> warm;
|
||
|
|
std::array<PreviewRawFrame *, PreviewFramePool::capacity> frames{};
|
||
|
|
for (size_t slot = 0; slot < warm.size(); ++slot) {
|
||
|
|
warm[slot] = pool.try_acquire();
|
||
|
|
pool.prepare(warm[slot], 32, 16);
|
||
|
|
frames[slot] = warm[slot].get();
|
||
|
|
}
|
||
|
|
for (auto &lease : warm)
|
||
|
|
lease.reset();
|
||
|
|
std::array<std::atomic<unsigned>, PreviewFramePool::capacity> owners{};
|
||
|
|
std::atomic<unsigned> ready{0}, finished{0}, acquired{0}, duplicates{0}, corruption{0};
|
||
|
|
std::atomic<bool> begin{false};
|
||
|
|
constexpr unsigned threads = 8, iterations = 1500;
|
||
|
|
std::array<std::thread, threads> work;
|
||
|
|
for (unsigned thread = 0; thread < threads; ++thread)
|
||
|
|
work[thread] = std::thread([&, thread] {
|
||
|
|
ready.fetch_add(1);
|
||
|
|
while (!begin.load())
|
||
|
|
std::this_thread::yield();
|
||
|
|
for (unsigned iteration = 0; iteration < iterations; ++iteration) {
|
||
|
|
auto lease = pool.try_acquire();
|
||
|
|
if (!lease) {
|
||
|
|
std::this_thread::yield();
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
size_t slot = 0;
|
||
|
|
while (slot < frames.size() && frames[slot] != lease.get())
|
||
|
|
++slot;
|
||
|
|
unsigned empty = 0;
|
||
|
|
if (slot == frames.size() || !owners[slot].compare_exchange_strong(empty, thread + 1)) {
|
||
|
|
duplicates.fetch_add(1);
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
pool.prepare(lease, 32, 16);
|
||
|
|
const auto marker = uint8_t(thread * 19 + iteration);
|
||
|
|
std::fill(lease->pixels.begin(), lease->pixels.end(), marker);
|
||
|
|
if (iteration % 8 == 0)
|
||
|
|
std::this_thread::yield();
|
||
|
|
if (!std::all_of(lease->pixels.begin(), lease->pixels.end(),
|
||
|
|
[marker](uint8_t value) { return value == marker; }))
|
||
|
|
corruption.fetch_add(1);
|
||
|
|
acquired.fetch_add(1);
|
||
|
|
owners[slot].store(0);
|
||
|
|
lease.reset();
|
||
|
|
}
|
||
|
|
finished.fetch_add(1);
|
||
|
|
});
|
||
|
|
while (ready.load() != threads)
|
||
|
|
std::this_thread::yield();
|
||
|
|
begin.store(true);
|
||
|
|
for (auto &thread : work)
|
||
|
|
thread.join();
|
||
|
|
const auto final = pool.snapshot();
|
||
|
|
check(finished.load() == threads && acquired.load() > 0,
|
||
|
|
"All concurrent producers complete a bounded set of acquisition attempts.");
|
||
|
|
check(duplicates.load() == 0 && corruption.load() == 0,
|
||
|
|
"Concurrent producers and retained frames never share an owner or corrupt another frame's pixels.");
|
||
|
|
check(count(final, "inUse") == 0 && count(final, "peakInUse") <= 3,
|
||
|
|
"Concurrent lease churn returns every slot and never exceeds the three-buffer limit.");
|
||
|
|
check(count(final, "allocations") == 3 && count(final, "allocatedSlots") == 3,
|
||
|
|
"Concurrent warmed callbacks reuse only the three allocated pixel buffers.");
|
||
|
|
check(std::all_of(owners.begin(), owners.end(), [](const auto &owner) { return owner.load() == 0; }),
|
||
|
|
"No thread leaves a stale external owner after lease destruction.");
|
||
|
|
}
|
||
|
|
void callback_diagnostics() {
|
||
|
|
struct SyntheticCallbackFailure {};
|
||
|
|
PreviewCallbackDiagnostics diagnostics;
|
||
|
|
const auto empty = diagnostics.snapshot(1000);
|
||
|
|
check(empty.at("lastCallbackUnixMs").is_null() && empty.at("lastCallbackAgeMs").is_null() &&
|
||
|
|
count(empty, "callbackEntries") == 0 && count(empty, "callbacksInFlight") == 0,
|
||
|
|
"Diagnostics distinguish a missing callback from an old callback.");
|
||
|
|
{
|
||
|
|
PreviewCallbackDiagnostics::Observation first(diagnostics, 32, 16, 4, 1200);
|
||
|
|
check(count(diagnostics.snapshot(1200), "callbacksInFlight") == 1,
|
||
|
|
"An active callback is visible before it completes.");
|
||
|
|
try {
|
||
|
|
PreviewCallbackDiagnostics::Observation nested(diagnostics, 64, 24, 4, 1210);
|
||
|
|
diagnostics.record_copy(std::chrono::steady_clock::now());
|
||
|
|
check(count(diagnostics.snapshot(1210), "callbacksInFlight") == 2,
|
||
|
|
"Overlapping callback scopes retain their own in-flight accounting.");
|
||
|
|
throw SyntheticCallbackFailure{};
|
||
|
|
} catch (const SyntheticCallbackFailure &) {
|
||
|
|
}
|
||
|
|
check(count(diagnostics.snapshot(1220), "callbacksInFlight") == 1 &&
|
||
|
|
count(diagnostics.snapshot(1220), "completedCallbacks") == 1,
|
||
|
|
"Exception unwinding completes one callback without clearing the other active callback.");
|
||
|
|
}
|
||
|
|
const auto final = diagnostics.snapshot(1260);
|
||
|
|
check(count(final, "callbackEntries") == 2 && count(final, "completedCallbacks") == 2 &&
|
||
|
|
count(final, "callbacksInFlight") == 0 && count(final, "copySamples") == 1,
|
||
|
|
"Callback and copy observations finish without leaking an in-flight count.");
|
||
|
|
check(final.at("lastCallbackUnixMs") == 1210 && final.at("lastCallbackAgeMs") == 50 &&
|
||
|
|
final.at("lastWidth") == 64 && final.at("lastHeight") == 24 && final.at("lastChannels") == 4,
|
||
|
|
"Diagnostics retain the latest received callback's timestamp and source dimensions.");
|
||
|
|
check(diagnostics.snapshot(1100).at("lastCallbackAgeMs") == 0,
|
||
|
|
"A backwards wall clock cannot produce a negative callback age.");
|
||
|
|
check(final.at("averageCopyMs").get<double>() >= 0 && final.at("averageCallbackMs").get<double>() >= 0,
|
||
|
|
"Callback cost diagnostics remain nonnegative without assuming a machine speed.");
|
||
|
|
}
|
||
|
|
} // namespace
|
||
|
|
int main() {
|
||
|
|
try {
|
||
|
|
no_vendor_dll();
|
||
|
|
capacity_and_ownership();
|
||
|
|
reuse_and_dimensions();
|
||
|
|
row_orientation();
|
||
|
|
concurrent_producers_and_encoder();
|
||
|
|
callback_diagnostics();
|
||
|
|
no_vendor_dll();
|
||
|
|
std::cout << "OFFLINE_TEST_FIXTURE: preview capture tests passed: " << passed
|
||
|
|
<< "; no SDK, device, HTTP or service action.\n";
|
||
|
|
return 0;
|
||
|
|
} catch (const std::exception &error) {
|
||
|
|
std::cerr << "FAIL (OFFLINE ONLY): " << error.what() << '\n';
|
||
|
|
return 1;
|
||
|
|
}
|
||
|
|
}
|