feat(video): recover camera previews and reduce encoding and playout cost
Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
This commit is contained in:
@@ -67,6 +67,7 @@ struct Frames final : StreamDelegate {
|
||||
size_t bytes = 0;
|
||||
uint64_t generation = 0, sequence = 0;
|
||||
std::atomic<int> codec{0};
|
||||
std::atomic<uint64_t> calibration_revision{0};
|
||||
std::atomic<bool> enabled{false};
|
||||
|
||||
void reset() {
|
||||
@@ -74,7 +75,7 @@ struct Frames final : StreamDelegate {
|
||||
queue.clear(); bytes = 0; ++generation;
|
||||
}
|
||||
void OnVideoData(const uint8_t* data, size_t size, int64_t timestamp,
|
||||
uint8_t, int stream_index) override {
|
||||
uint8_t stream_type, int stream_index) override {
|
||||
if (!enabled || !data || !size || size > MAX_PACKET || stream_index < 0 || stream_index > 1) return;
|
||||
// SDK owns the callback bytes. Copy into a bounded queue; never block
|
||||
// a vendor callback on a browser, disk, decoder or Python interpreter.
|
||||
@@ -84,7 +85,8 @@ struct Frames final : StreamDelegate {
|
||||
queue.clear(); bytes = 0; ++generation;
|
||||
}
|
||||
queue.push_back({{++sequence, generation, timestamp, stream_index,
|
||||
codec.load(), uint32_t(size)}, {data, data + size}});
|
||||
codec.load(), uint32_t(size), stream_type,
|
||||
calibration_revision.load()}, {data, data + size}});
|
||||
bytes += size;
|
||||
} catch (...) {
|
||||
// A memory allocation failure drops data; it must not unwind into
|
||||
@@ -171,12 +173,20 @@ struct mc_x4 {
|
||||
// Read-only metadata from this session's camera. A missing/unknown
|
||||
// calibration must not take down camera control or the raw lens feed.
|
||||
calibration = "null";
|
||||
const auto revision = ++frames->calibration_revision;
|
||||
try {
|
||||
auto param = camera->GetPreviewParam();
|
||||
const auto count = param.GetCalibrationCount();
|
||||
if (!count || count > 4) return;
|
||||
std::ostringstream out;
|
||||
out << "{\"offsets\":[";
|
||||
out << "{\"revision\":" << revision
|
||||
<< ",\"camera_name\":" << quote(param.camera_name, 128)
|
||||
<< ",\"encode_type\":" << int(param.encode_type)
|
||||
<< ",\"delay_timestamp\":" << param.delay_timestamp
|
||||
<< ",\"sweep_time\":" << param.sweep_time
|
||||
<< ",\"acceleration_range\":" << param.acceleration_range
|
||||
<< ",\"gyro_range\":" << param.gyro_range
|
||||
<< ",\"offsets\":[";
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (i) out << ',';
|
||||
out << quote(param.GetCalibration(i), 8192);
|
||||
@@ -318,6 +328,7 @@ struct mc_x4 {
|
||||
params.enable_audio = false; params.enable_gyro = false; params.using_lrv = false;
|
||||
params.video_resolution = RES_1920_960P30; params.lrv_video_resulution = RES_1920_960P30;
|
||||
params.video_bitrate = 4000000;
|
||||
read_preview_calibration();
|
||||
frames->reset(); frames->codec = int(camera->GetVideoEncodeType()); frames->enabled = true;
|
||||
preview = -1;
|
||||
bool ok = camera->StartLiveStreaming(params);
|
||||
@@ -392,7 +403,7 @@ struct mc_x4 {
|
||||
};
|
||||
|
||||
extern "C" {
|
||||
int mc_x4_abi(void) { return 1; }
|
||||
int mc_x4_abi(void) { return 2; }
|
||||
mc_x4* mc_x4_open(const char* serial, const char* log_directory) {
|
||||
try {
|
||||
if (!serial || !*serial || std::strlen(serial) > 256 || !log_directory || !*log_directory) return nullptr;
|
||||
@@ -439,6 +450,21 @@ const char* mc_x4_call(mc_x4* handle, int action, int mode, const char* key, dou
|
||||
return handle->result.c_str();
|
||||
} catch (...) { return UNKNOWN; }
|
||||
}
|
||||
int mc_x4_download(mc_x4* handle, const char* remote, const char* local, mc_x4_download_progress progress) {
|
||||
if (!handle || !remote || !local || !*remote || !*local ||
|
||||
std::strlen(remote) > 1024 || std::strlen(local) > 4096) return -1;
|
||||
try {
|
||||
if (!handle->camera->IsConnected() || handle->camera->CaptureCurrentStatus()) return -1;
|
||||
const auto files = handle->camera->GetCameraFilesList();
|
||||
if (files.size() > 100000 || !contains(files, std::string(remote))) return -1;
|
||||
return handle->camera->DownloadCameraFile(remote, local, [progress](int64_t downloaded, int64_t total) {
|
||||
if (progress) progress(downloaded, total);
|
||||
}) ? 1 : 0;
|
||||
} catch (...) { return 0; }
|
||||
}
|
||||
void mc_x4_cancel_download(mc_x4* handle) {
|
||||
try { if (handle) handle->camera->CancelDownload(); } catch (...) {}
|
||||
}
|
||||
int mc_x4_read_video(mc_x4* handle, mc_x4_video* info, uint8_t* buffer, size_t capacity) {
|
||||
if (!handle || !info || !buffer) return -1;
|
||||
try {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Private ABI v1. One handle in each physically isolated camera worker. The
|
||||
// Private ABI v2. One handle in each physically isolated camera worker. The
|
||||
// caller must restrict USB access BEFORE loading this library or discovering.
|
||||
typedef struct mc_x4 mc_x4;
|
||||
enum mc_x4_action {
|
||||
@@ -28,6 +28,8 @@ typedef struct mc_x4_video {
|
||||
int32_t stream_index;
|
||||
int32_t codec; // 0 = H264, 1 = H265
|
||||
uint32_t bytes;
|
||||
int32_t stream_type; // original CameraSDK callback marker, NOT a codec enum
|
||||
uint64_t calibration_revision; // identifies this preview's exact metadata
|
||||
} mc_x4_video;
|
||||
|
||||
MC_X4_API int mc_x4_abi(void);
|
||||
@@ -35,6 +37,12 @@ MC_X4_API mc_x4* mc_x4_open(const char* expected_serial, const char* private_log
|
||||
// JSON result owned by the handle; copy before the next call. Calls are
|
||||
// serialized by the worker. No vendor exception or C++ object crosses the ABI.
|
||||
MC_X4_API const char* mc_x4_call(mc_x4*, int action, int mode, const char* key, double value);
|
||||
// Serialized with control calls. Only an exact current camera-list entry is
|
||||
// admitted. Destination is selected inside the private worker, never by a UI.
|
||||
typedef void (*mc_x4_download_progress)(int64_t downloaded, int64_t total);
|
||||
MC_X4_API int mc_x4_download(mc_x4*, const char* remote, const char* local, mc_x4_download_progress);
|
||||
// The SDK explicitly provides cancellation for an in-progress download.
|
||||
MC_X4_API void mc_x4_cancel_download(mc_x4*);
|
||||
MC_X4_API int mc_x4_read_video(mc_x4*, mc_x4_video*, uint8_t* buffer, size_t capacity);
|
||||
// Does not call StopRecording or change auto-stop-on-disconnect policy.
|
||||
MC_X4_API void mc_x4_close(mc_x4*);
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
// Bounded rendering qualification. No CameraSDK, USB access or live-view claim.
|
||||
#include <ins_realtime_stitcher.h>
|
||||
#include <ins_stitcher.h>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
template <class T> T read(std::istream& file) {
|
||||
T value{};
|
||||
if (!file.read(reinterpret_cast<char*>(&value), sizeof(value)))
|
||||
throw std::runtime_error("Truncated synthetic input");
|
||||
return value;
|
||||
}
|
||||
std::string text(std::istream& file, uint32_t limit, bool allow_empty = false) {
|
||||
auto size = read<uint32_t>(file);
|
||||
if ((!size && !allow_empty) || size > limit) throw std::runtime_error("Invalid synthetic metadata");
|
||||
std::string value(size, '\0');
|
||||
if (!file.read(value.data(), size)) throw std::runtime_error("Truncated metadata");
|
||||
return value;
|
||||
}
|
||||
struct Packet { int64_t timestamp; std::string data; uint8_t type; int index; };
|
||||
struct Output {
|
||||
std::atomic<int> frames{0}, error{0}, unsupported{0};
|
||||
std::mutex mutex;
|
||||
std::string error_text;
|
||||
std::vector<uint8_t> first, last;
|
||||
int64_t first_timestamp = 0, last_timestamp = 0;
|
||||
int first_width = 0, first_height = 0, first_format = -1;
|
||||
std::chrono::steady_clock::time_point first_at{}, last_at{};
|
||||
std::map<int64_t, uint64_t> arrivals;
|
||||
struct Timing { int64_t timestamp; uint64_t output_ns; int64_t reader_latency_ns; };
|
||||
std::vector<Timing> timings;
|
||||
};
|
||||
uint64_t monotonic_ns() {
|
||||
timespec value{};
|
||||
if (clock_gettime(CLOCK_MONOTONIC, &value)) throw std::runtime_error("Monotonic clock failed");
|
||||
return static_cast<uint64_t>(value.tv_sec) * 1000000000ULL + value.tv_nsec;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 4 && argc != 5) return 4;
|
||||
std::cout << "{\"phase\":\"render_process_started\"}" << std::endl;
|
||||
try {
|
||||
const bool live = std::string(argv[2]) == "-";
|
||||
const std::string stitch_type = argc == 5 ? argv[4] : "dynamic";
|
||||
if ((stitch_type != "dynamic" && stitch_type != "template") || (live && argc == 5))
|
||||
throw std::runtime_error("Unqualified stitch mode");
|
||||
std::ifstream file;
|
||||
if (!live) file.open(argv[2], std::ios::binary);
|
||||
std::istream& input = live ? std::cin : file;
|
||||
char magic[8]{};
|
||||
if (!input.read(magic, 8)) throw std::runtime_error("Truncated input");
|
||||
const bool recorded = std::memcmp(magic, "MCX4P002", 8) == 0;
|
||||
if (live ? std::memcmp(magic, "MCX4L001", 8)
|
||||
: (!recorded && std::memcmp(magic, "MCX4P001", 8)))
|
||||
throw std::runtime_error("Unexpected input profile");
|
||||
const auto model = text(input, 128);
|
||||
auto count = read<uint32_t>(input);
|
||||
if (!count || count > 4) throw std::runtime_error("Invalid calibration count");
|
||||
std::vector<std::string> offsets;
|
||||
// CameraSDK preserves empty optional calibration slots. Keep their
|
||||
// positions intact when forwarding the exact vector to MediaSDK.
|
||||
for (uint32_t i = 0; i < count; ++i) offsets.push_back(text(input, 8192, true));
|
||||
if (std::all_of(offsets.begin(), offsets.end(), [](const auto& v) { return v.empty(); }))
|
||||
throw std::runtime_error("Missing factory calibration");
|
||||
uint32_t sizes[4];
|
||||
for (auto& size : sizes) {
|
||||
size = read<uint32_t>(input);
|
||||
if (!size || size > 16384) throw std::runtime_error("Invalid calibration geometry");
|
||||
}
|
||||
auto x = read<int32_t>(input), y = read<int32_t>(input);
|
||||
if (x < 0 || y < 0 || x > 16384 || y > 16384)
|
||||
throw std::runtime_error("Invalid crop origin");
|
||||
const auto codec = (recorded || live) ? read<uint32_t>(input) : 0u;
|
||||
if (codec > 1) throw std::runtime_error("Invalid codec");
|
||||
count = live ? 0 : read<uint32_t>(input);
|
||||
if (!live && (!count || count > (recorded ? 128u : 64u)))
|
||||
throw std::runtime_error("Invalid packet count");
|
||||
std::vector<Packet> packets;
|
||||
size_t total = 0;
|
||||
int64_t previous[2] = {0, 0};
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
auto timestamp = read<int64_t>(input);
|
||||
const auto type = recorded ? read<uint32_t>(input) : 0x20u;
|
||||
const auto index = recorded ? read<uint32_t>(input) : 0u;
|
||||
if (type > 255 || index > 1) throw std::runtime_error("Invalid callback routing");
|
||||
// Parameter NALs and the associated access unit share a timestamp.
|
||||
if (timestamp <= 0 || timestamp > 9000000000000000LL || timestamp < previous[index])
|
||||
throw std::runtime_error("Invalid source timestamp");
|
||||
previous[index] = timestamp;
|
||||
auto data = text(input, (recorded ? 4 : 1) * 1024 * 1024);
|
||||
total += data.size();
|
||||
if (total > 8 * 1024 * 1024) throw std::runtime_error("Synthetic input exceeds bound");
|
||||
packets.push_back({timestamp, std::move(data), static_cast<uint8_t>(type),
|
||||
static_cast<int>(index)});
|
||||
}
|
||||
if (!live && input.peek() != std::ifstream::traits_type::eof())
|
||||
throw std::runtime_error("Trailing synthetic input");
|
||||
ins::InitEnv();
|
||||
ins::SetLogPath(std::string(argv[1]) + "/media.log");
|
||||
ins::SetLogLevel(ins::InsLogLevel::VERBOSE);
|
||||
ins::SetModelFileRootDir(argv[3]);
|
||||
ins::CameraInfo info;
|
||||
info.cameraName = model;
|
||||
info.decode_type = static_cast<ins::VideoDecodeType>(codec);
|
||||
info.SetCalibration(offsets, sizes[0], sizes[1], sizes[2], sizes[3], x, y);
|
||||
// Vendor callbacks own their state, including any copy retained by
|
||||
// global SDK teardown. No callback refers to main's stack lifetime.
|
||||
auto output = std::make_shared<Output>();
|
||||
auto& frames = output->frames; auto& error = output->error;
|
||||
auto& unsupported = output->unsupported; auto& mutex = output->mutex;
|
||||
auto& first = output->first; auto& error_text = output->error_text;
|
||||
auto& first_timestamp = output->first_timestamp;
|
||||
auto& first_width = output->first_width; auto& first_height = output->first_height;
|
||||
auto& first_format = output->first_format;
|
||||
first.reserve(960 * 480 * 3);
|
||||
auto stitcher = std::make_unique<ins::RealTimeStitcher>();
|
||||
stitcher->SetSoftwareCodecUsage(true, true);
|
||||
stitcher->SetCameraInfo(info);
|
||||
stitcher->SetStitchType(stitch_type == "template" ? ins::STITCH_TYPE::TEMPLATE : ins::STITCH_TYPE::DYNAMICSTITCH);
|
||||
stitcher->EnableFlowState(false);
|
||||
stitcher->EnableDirectionLock(false);
|
||||
stitcher->SetVideoDelayMs(0);
|
||||
stitcher->SetOutputSize(960, 480);
|
||||
stitcher->SetStitchStateCallback([output](int code, const char* message) {
|
||||
if (!code) return;
|
||||
output->error = code;
|
||||
std::lock_guard<std::mutex> lock(output->mutex);
|
||||
output->error_text.assign(message ? message : "", message ? ::strnlen(message, 512) : 0);
|
||||
});
|
||||
stitcher->SetStitchRealTimeDataCallback([output](uint8_t* data[4], int stride[4], int width, int height, int format, int64_t timestamp) {
|
||||
auto& frames = output->frames; auto& unsupported = output->unsupported;
|
||||
auto& mutex = output->mutex; auto& first = output->first;
|
||||
auto& first_timestamp = output->first_timestamp;
|
||||
auto& first_width = output->first_width; auto& first_height = output->first_height;
|
||||
auto& first_format = output->first_format;
|
||||
// Copy only admitted packed formats; unknown formats are reported,
|
||||
// not reinterpreted as RGBA. Callback buffers remain vendor-owned.
|
||||
const int callback = ++frames;
|
||||
if (callback <= 3) {
|
||||
std::cout << "{\"phase\":\"output_layout\",\"width\":" << width
|
||||
<< ",\"height\":" << height << ",\"format\":" << format
|
||||
<< ",\"strides\":[" << stride[0] << ',' << stride[1] << ','
|
||||
<< stride[2] << ',' << stride[3] << "]}" << std::endl;
|
||||
}
|
||||
// The exact 3.1.5 runtime returns format=0 with one packed
|
||||
// four-byte plane, matching the shipped example's RGBA callback.
|
||||
// Its header incorrectly describes the identifier as AVPixelFormat.
|
||||
// Pin this observed layout; never reinterpret 0 as planar YUV.
|
||||
constexpr int bytes = 4;
|
||||
if (format != 0 || width <= 0 || height <= 0 || width > 4096 || height > 2048 ||
|
||||
width * height > 4 * 1024 * 1024 || width != height * 2 ||
|
||||
!data[0] || data[1] || data[2] || data[3] ||
|
||||
stride[0] != width * bytes || stride[1] || stride[2] || stride[3]) {
|
||||
++unsupported; return;
|
||||
}
|
||||
std::unique_lock<std::mutex> lock(mutex, std::try_to_lock);
|
||||
if (!lock) return;
|
||||
if (!first.empty() && (width != first_width || height != first_height)) {
|
||||
++unsupported; return;
|
||||
}
|
||||
try {
|
||||
output->last.resize(width * height * 3);
|
||||
for (int row = 0; row < height; ++row) {
|
||||
const auto* line = data[0] + row * stride[0];
|
||||
for (int col = 0; col < width; ++col) {
|
||||
const auto* pixel = line + col * bytes;
|
||||
std::memcpy(output->last.data() + (row * width + col) * 3, pixel, 3);
|
||||
}
|
||||
}
|
||||
output->last_at = std::chrono::steady_clock::now();
|
||||
output->last_timestamp = timestamp;
|
||||
if (output->timings.size() < 2000) {
|
||||
const auto now = monotonic_ns();
|
||||
const auto found = output->arrivals.find(timestamp);
|
||||
output->timings.push_back({timestamp, now,
|
||||
found == output->arrivals.end() ? -1 : static_cast<int64_t>(now - found->second)});
|
||||
}
|
||||
if (first.empty()) {
|
||||
first = output->last;
|
||||
first_timestamp = timestamp;
|
||||
first_width = width;
|
||||
first_height = height;
|
||||
first_format = format;
|
||||
output->first_at = output->last_at;
|
||||
}
|
||||
} catch (...) { ++unsupported; }
|
||||
});
|
||||
std::cout << "{\"phase\":\"start_stitch\",\"input\":\""
|
||||
<< (live ? "live-original-callbacks" : recorded ? "original-callback-sample" : "synthetic") << "\"}" << std::endl;
|
||||
stitcher->StartStitch();
|
||||
const auto ready_at = monotonic_ns();
|
||||
if (live) std::cout << "{\"phase\":\"live_ready\",\"monotonic_ns\":" << ready_at << '}' << std::endl;
|
||||
// A short all-intra source is replayed with increasing timestamps to
|
||||
// cover decoder startup buffering. This is bounded functional input,
|
||||
// not a sustained FPS measurement or a real camera recording.
|
||||
const auto cycle_duration = live ? 0 : packets.back().timestamp - packets.front().timestamp + 333333;
|
||||
int submitted = 0;
|
||||
int64_t live_last_timestamp = 0;
|
||||
uint64_t first_input_at = 0;
|
||||
while (live && !error.load()) {
|
||||
auto size = read<uint32_t>(input);
|
||||
if (!size) break;
|
||||
if (size > 4 * 1024 * 1024 || ++submitted > 900 || (total += size) > 32 * 1024 * 1024)
|
||||
throw std::runtime_error("Live input exceeds bounds");
|
||||
auto timestamp = read<int64_t>(input);
|
||||
auto type = read<uint32_t>(input), index = read<uint32_t>(input);
|
||||
auto received = read<uint64_t>(input);
|
||||
if (!first_input_at) first_input_at = received;
|
||||
if (type > 255 || index > 1 || timestamp <= 0 || timestamp < previous[index] ||
|
||||
received > monotonic_ns() || monotonic_ns() - received > 5000000000ULL)
|
||||
throw std::runtime_error("Invalid or stale live callback metadata");
|
||||
previous[index] = timestamp;
|
||||
live_last_timestamp = timestamp;
|
||||
std::string data(size, '\0');
|
||||
if (!input.read(data.data(), size)) throw std::runtime_error("Truncated live packet");
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
output->arrivals.emplace(timestamp, received);
|
||||
while (output->arrivals.size() > 1024) output->arrivals.erase(output->arrivals.begin());
|
||||
}
|
||||
stitcher->HandleVideoData(reinterpret_cast<const uint8_t*>(data.data()),
|
||||
data.size(), timestamp, static_cast<uint8_t>(type), static_cast<int>(index));
|
||||
}
|
||||
auto input_ended_at = monotonic_ns();
|
||||
const size_t limit = live ? 0 : recorded ? packets.size() : 48;
|
||||
for (size_t i = 0; i < limit && !error.load() && (recorded || !frames.load()); ++i) {
|
||||
const auto& packet = packets[i % packets.size()];
|
||||
const auto timestamp = packet.timestamp + (recorded ? 0 : (i / packets.size()) * cycle_duration);
|
||||
if (recorded) {
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
output->arrivals.emplace(timestamp, monotonic_ns());
|
||||
}
|
||||
// Pinned 3.1.5 dispatches the combined stream with 0x20; codec
|
||||
// enums 0/1 are silently ignored here despite the header wording.
|
||||
// Synthetic fixture only. Live integration MUST preserve the
|
||||
// CameraSDK callback's original streamType instead of inferring it.
|
||||
stitcher->HandleVideoData(reinterpret_cast<const uint8_t*>(packet.data.data()),
|
||||
packet.data.size(), timestamp, packet.type, packet.index);
|
||||
++submitted;
|
||||
// Preserve vendor timestamps exactly, as the shipped camera/media
|
||||
// example does. Current X4 callback deltas are 33/34 over ~30 fps,
|
||||
// despite the MediaSDK header's microsecond wording. This fixed
|
||||
// replay pacing bounds decoder pressure; it is not an FPS test.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(recorded ? 30 : 150));
|
||||
}
|
||||
if (!live) input_ended_at = monotonic_ns();
|
||||
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(20);
|
||||
while (!error.load() && std::chrono::steady_clock::now() < deadline) {
|
||||
bool drained = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
drained = !first.empty() && ((!recorded && !live) ||
|
||||
output->last_timestamp >= (live ? live_last_timestamp : packets.back().timestamp) ||
|
||||
std::chrono::steady_clock::now() - output->last_at > std::chrono::seconds(2));
|
||||
}
|
||||
if (drained) break;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
// The public 3.1.5 destructor explicitly stops an active session and
|
||||
// releases resources. Qualify that documented single teardown path,
|
||||
// with callback state still alive, before examining any output. This
|
||||
// does not skip either instance destruction or global SDK teardown.
|
||||
std::cout << "{\"phase\":\"destroy_stitcher\"}" << std::endl;
|
||||
stitcher.reset();
|
||||
std::cout << "{\"phase\":\"stitcher_destroyed\"}" << std::endl;
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
const bool valid = !first.empty() && first.size() == static_cast<size_t>(first_width * first_height * 3) &&
|
||||
(live || *std::min_element(first.begin(), first.end()) < *std::max_element(first.begin(), first.end()));
|
||||
if (valid) {
|
||||
std::ofstream output(live ? "live-camera.ppm" : recorded ? "recorded-camera.ppm" : "synthetic.ppm", std::ios::binary);
|
||||
output << "P6\n" << first_width << ' ' << first_height << "\n255\n";
|
||||
output.write(reinterpret_cast<const char*>(first.data()), first.size());
|
||||
if (!output) throw std::runtime_error("Cannot save first-frame evidence");
|
||||
}
|
||||
if (valid && (recorded || live)) {
|
||||
std::ofstream last_file(live ? "live-camera-last.ppm" : "recorded-camera-last.ppm", std::ios::binary);
|
||||
last_file << "P6\n" << first_width << ' ' << first_height << "\n255\n";
|
||||
last_file.write(reinterpret_cast<const char*>(output->last.data()), output->last.size());
|
||||
if (!last_file) throw std::runtime_error("Cannot save last-frame evidence");
|
||||
}
|
||||
if (live || recorded) {
|
||||
std::ofstream timing("callback-timing.jsonl");
|
||||
timing << "{\"ready_ns\":" << ready_at << ",\"first_input_ns\":" << first_input_at
|
||||
<< ",\"input_ended_ns\":" << input_ended_at << "}\n";
|
||||
for (const auto& value : output->timings)
|
||||
timing << "{\"vendor_timestamp\":" << value.timestamp << ",\"output_ns\":" << value.output_ns
|
||||
<< ",\"reader_to_output_ns\":" << value.reader_latency_ns << "}\n";
|
||||
if (!timing) throw std::runtime_error("Cannot save live timing evidence");
|
||||
}
|
||||
std::cout << "{\"synthetic_frame_verified\":" << (valid && !recorded && !live ? "true" : "false")
|
||||
<< ",\"recorded_camera_frame_verified\":" << (valid && recorded ? "true" : "false")
|
||||
<< ",\"live_camera_frame_verified\":" << (valid && live ? "true" : "false") << ",\"callbacks\":" << frames.load()
|
||||
<< ",\"packets_submitted\":" << submitted
|
||||
<< ",\"unsupported_callbacks\":" << unsupported.load()
|
||||
<< ",\"width\":" << first_width << ",\"height\":" << first_height
|
||||
<< ",\"pixel_format\":" << first_format
|
||||
<< ",\"pixel_contract\":\"mediasdk-3.1.5-packed-rgba-format-0\""
|
||||
<< ",\"stitch_type\":\"" << stitch_type << "\""
|
||||
<< ",\"callback_span_ms\":" << std::chrono::duration_cast<std::chrono::milliseconds>(output->last_at - output->first_at).count()
|
||||
<< ",\"last_vendor_timestamp\":" << output->last_timestamp
|
||||
<< ",\"sdk_error\":" << error.load() << ",\"vendor_timestamp\":" << first_timestamp << '}' << std::endl;
|
||||
if (!error_text.empty()) std::cerr << error_text << std::endl;
|
||||
return valid && !error.load() && !unsupported.load() ? 0 : 5;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << std::endl;
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// One selected frame from an owned camera original. No CameraSDK or USB access.
|
||||
#include <ins_stitcher.h>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
|
||||
bool jpeg_complete(const std::filesystem::path& path) {
|
||||
if (!std::filesystem::exists(path) || std::filesystem::file_size(path) < 4) return false;
|
||||
std::ifstream stream(path, std::ios::binary);
|
||||
unsigned char bytes[2]{};
|
||||
stream.read(reinterpret_cast<char*>(bytes), 2);
|
||||
if (bytes[0] != 0xff || bytes[1] != 0xd8) return false;
|
||||
stream.seekg(-2, std::ios::end);
|
||||
stream.read(reinterpret_cast<char*>(bytes), 2);
|
||||
return bool(stream) && bytes[0] == 0xff && bytes[1] == 0xd9;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 5) return 4;
|
||||
try {
|
||||
const double seconds = std::stod(argv[4]);
|
||||
if (!std::isfinite(seconds) || seconds < 0 || seconds > 240) return 4;
|
||||
ins::InitEnv();
|
||||
ins::SetLogPath(argv[1]);
|
||||
ins::SetLogLevel(ins::InsLogLevel::WARNING);
|
||||
ins::SetModelFileRootDir(argv[3]);
|
||||
ins::MediaFileInfo info{};
|
||||
if (!ins::GetMediaFileInfo({argv[2]}, info)) return 5;
|
||||
std::cout << "{\"phase\":\"original_metadata\",\"width\":" << info.width
|
||||
<< ",\"height\":" << info.height << ",\"fps\":" << info.fps
|
||||
<< ",\"duration_ms\":" << info.duration_ms << "}" << std::endl;
|
||||
if (!std::isfinite(info.fps) || info.fps <= 0 || info.fps > 120 ||
|
||||
seconds * 1000 >= info.duration_ms) return 6;
|
||||
const auto frame = uint64_t(std::llround(seconds * info.fps));
|
||||
auto error = std::make_shared<std::atomic<int>>(0);
|
||||
auto progress = std::make_shared<std::atomic<int>>(-1);
|
||||
auto stitcher = std::make_unique<ins::VideoStitcher>();
|
||||
stitcher->SetInputPath({argv[2]});
|
||||
stitcher->EnableCuda(false);
|
||||
stitcher->SetSoftwareCodecUsage(true, true);
|
||||
stitcher->SetImageProcessingAccelType(ins::ImageProcessingAccel::kCPU);
|
||||
stitcher->EnableFlowState(false);
|
||||
stitcher->EnableDirectionLock(false);
|
||||
stitcher->EnableColorPlus(false);
|
||||
stitcher->EnableDenoise(false);
|
||||
stitcher->SetStitchType(ins::STITCH_TYPE::DYNAMICSTITCH);
|
||||
stitcher->EnableStitchFusion(true);
|
||||
stitcher->SetOutputSize(1920, 960);
|
||||
std::filesystem::create_directory("frames");
|
||||
stitcher->SetImageSequenceInfo("frames", ins::IMAGE_TYPE::JPEG);
|
||||
stitcher->SetExportFrameSequence({frame});
|
||||
stitcher->SetStitchStateCallback([error](int value, const char*) {
|
||||
if (value) *error = value;
|
||||
std::cout << "{\"phase\":\"state_callback\",\"code\":" << value << "}" << std::endl;
|
||||
});
|
||||
stitcher->SetStitchProgressCallback([error, progress](int value, int code) {
|
||||
*progress = value;
|
||||
if (code) *error = code;
|
||||
});
|
||||
std::cout << "{\"phase\":\"original_stitch_start\",\"frame\":" << frame << "}" << std::endl;
|
||||
stitcher->StartStitch();
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(35);
|
||||
const auto target = std::filesystem::path("frames") / (std::to_string(frame) + ".jpg");
|
||||
// Selected-frame export can leave GetStitchProgress at zero. This is
|
||||
// a bounded one-image job: stop through the documented destructor
|
||||
// after that exact complete JPEG exists, retaining the real progress
|
||||
// telemetry. Do not claim natural whole-video completion.
|
||||
while (!error->load() && std::chrono::steady_clock::now() < deadline) {
|
||||
if (jpeg_complete(target)) {
|
||||
const auto size = std::filesystem::file_size(target);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
if (jpeg_complete(target) && std::filesystem::file_size(target) == size) break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
std::cout << "{\"phase\":\"original_stitch_result\",\"progress\":"
|
||||
<< stitcher->GetStitchProgress() << ",\"callback_progress\":" << progress->load()
|
||||
<< ",\"error\":" << error->load() << "}" << std::endl;
|
||||
for (const auto& feature : stitcher->GetFeatureStatusMap()) {
|
||||
std::cout << "sdk_feature " << feature.first << " " << feature.second << std::endl;
|
||||
}
|
||||
stitcher.reset();
|
||||
size_t count = 0;
|
||||
for (const auto& item : std::filesystem::directory_iterator("frames")) {
|
||||
if (item.is_regular_file() && item.file_size() > 0) ++count;
|
||||
}
|
||||
std::cout << "{\"phase\":\"original_stitch_destroyed\",\"files\":" << count << "}" << std::endl;
|
||||
return error->load() == 0 && count == 1 && jpeg_complete(target) ? 0 : 7;
|
||||
} catch (...) {
|
||||
std::cerr << "Original qualification failed" << std::endl;
|
||||
return 8;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Capability qualification only. No CameraSDK linkage, discovery or USB calls.
|
||||
#include <ins_realtime_stitcher.h>
|
||||
#include <ins_stitcher.h>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 2) return 4;
|
||||
std::cout << "{\"phase\":\"process_started\"}" << std::endl;
|
||||
try {
|
||||
ins::InitEnv();
|
||||
ins::SetLogPath(argv[1]);
|
||||
ins::SetLogLevel(ins::InsLogLevel::WARNING);
|
||||
std::cout << "{\"phase\":\"environment_initialized\"}" << std::endl;
|
||||
{
|
||||
ins::RealTimeStitcher stitcher;
|
||||
stitcher.SetSoftwareCodecUsage(true, true);
|
||||
stitcher.EnableFlowState(false);
|
||||
stitcher.EnableDirectionLock(false);
|
||||
stitcher.SetStitchType(ins::STITCH_TYPE::DYNAMICSTITCH);
|
||||
stitcher.SetOutputSize(960, 480);
|
||||
std::cout << "{\"phase\":\"realtime_constructed\"}" << std::endl;
|
||||
}
|
||||
std::cout << "{\"phase\":\"realtime_destroyed\",\"frame_verified\":false}" << std::endl;
|
||||
return 0;
|
||||
} catch (const std::exception&) {
|
||||
std::cerr << "MediaSDK qualification raised an exception" << std::endl;
|
||||
return 2;
|
||||
} catch (...) {
|
||||
std::cerr << "MediaSDK qualification raised an unknown exception" << std::endl;
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ class Header(ctypes.Structure):
|
||||
("stream_index", ctypes.c_int32),
|
||||
("codec", ctypes.c_int32),
|
||||
("bytes", ctypes.c_uint32),
|
||||
("stream_type", ctypes.c_int32),
|
||||
("calibration_revision", ctypes.c_uint64),
|
||||
]
|
||||
|
||||
|
||||
@@ -56,6 +58,9 @@ def library(folder):
|
||||
capture_output=True,
|
||||
)
|
||||
api = ctypes.CDLL(str(target))
|
||||
api.mc_x4_abi.restype = ctypes.c_int
|
||||
assert api.mc_x4_abi() == 2
|
||||
assert ctypes.sizeof(Header) == 48
|
||||
api.mc_x4_open.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
|
||||
api.mc_x4_open.restype = ctypes.c_void_p
|
||||
api.mc_x4_call.argtypes = [
|
||||
@@ -98,9 +103,33 @@ def test_details_include_session_identity_and_optics_without_starting_preview(ca
|
||||
result = call(camera, 1)["result"]
|
||||
assert result["serial"] == "SYNTHETIC-X4"
|
||||
assert len(result["preview_calibration"]["offsets"]) == 1
|
||||
assert {
|
||||
k: result["preview_calibration"][k]
|
||||
for k in (
|
||||
"camera_name",
|
||||
"encode_type",
|
||||
"delay_timestamp",
|
||||
"sweep_time",
|
||||
"acceleration_range",
|
||||
"gyro_range",
|
||||
"revision",
|
||||
)
|
||||
} == {
|
||||
"camera_name": "Insta360 X4",
|
||||
"encode_type": 0,
|
||||
"delay_timestamp": 127,
|
||||
"sweep_time": 391,
|
||||
"acceleration_range": 16,
|
||||
"gyro_range": 2000,
|
||||
"revision": 1,
|
||||
}
|
||||
assert result["preview_calibration"]["crop"] == {
|
||||
"source_width": 1920, "source_height": 960,
|
||||
"width": 1920, "height": 960, "x": 0, "y": 0,
|
||||
"source_width": 1920,
|
||||
"source_height": 960,
|
||||
"width": 1920,
|
||||
"height": 960,
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
}
|
||||
assert api.test_count(3) == 0 and api.test_count(6) == 0
|
||||
|
||||
@@ -165,6 +194,12 @@ def test_frames_copy_vendor_memory_preserve_stream_and_bound_backlog(camera):
|
||||
info, buffer = Header(), (ctypes.c_uint8 * 24)()
|
||||
assert api.mc_x4_read_video(handle, ctypes.byref(info), buffer, 24) == 1
|
||||
assert (info.stream_index, info.timestamp, info.bytes) == (1, 12345, 24)
|
||||
assert info.stream_type == 0x21 and info.codec == 0
|
||||
assert (
|
||||
info.calibration_revision
|
||||
== call(camera, 1)["result"]["preview_calibration"]["revision"]
|
||||
== 2
|
||||
)
|
||||
assert bytes(buffer) == bytes([91]) * 24
|
||||
generation = info.generation
|
||||
for i in range(65):
|
||||
@@ -173,6 +208,11 @@ def test_frames_copy_vendor_memory_preserve_stream_and_bound_backlog(camera):
|
||||
assert info.generation > generation # decoder must reset after this loss
|
||||
assert bytes(buffer) == bytes([64]) * 24
|
||||
assert api.mc_x4_read_video(handle, ctypes.byref(info), buffer, 24) == 0
|
||||
call(camera, 5)
|
||||
call(camera, 4)
|
||||
api.test_packet(0, 24, 17)
|
||||
assert api.mc_x4_read_video(handle, ctypes.byref(info), buffer, 24) == 1
|
||||
assert info.calibration_revision == 3 and info.stream_type == 0x20
|
||||
|
||||
|
||||
def test_camera_files_are_bounded_pages(camera):
|
||||
@@ -191,6 +231,28 @@ def test_early_camera_stop_notification_wins_over_start_acknowledgement(camera):
|
||||
assert api.test_count(4) == 1
|
||||
|
||||
|
||||
def test_download_requires_current_list_entry_and_never_stops_recording(camera):
|
||||
api, handle = camera
|
||||
progress_type = ctypes.CFUNCTYPE(None, ctypes.c_int64, ctypes.c_int64)
|
||||
api.mc_x4_download.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, progress_type]
|
||||
api.mc_x4_download.restype = ctypes.c_int
|
||||
observed = []
|
||||
callback = progress_type(lambda current, total: observed.append((current, total)))
|
||||
with tempfile.TemporaryDirectory(dir=ROOT / "build") as directory:
|
||||
path = Path(directory) / "original.insv"
|
||||
args = (handle, b"/DCIM/synthetic_0.insv", str(path).encode(), callback)
|
||||
assert api.mc_x4_download(handle, b"/DCIM/not-listed.insv", str(path).encode(), callback) == -1
|
||||
assert not path.exists()
|
||||
api.test_recording(1)
|
||||
assert api.mc_x4_download(*args) == -1
|
||||
assert not path.exists() and api.test_count(5) == 0
|
||||
api.test_recording(0)
|
||||
assert api.mc_x4_download(*args) == 1
|
||||
assert path.read_bytes() == b"synthetic camera original"
|
||||
assert observed == [(25, 25)]
|
||||
assert api.test_count(3) == 0 and api.test_count(5) == 0
|
||||
|
||||
|
||||
def test_unavailable_calibration_preserves_camera_control(library):
|
||||
for mode in (1, 2):
|
||||
library.test_calibration(mode)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <camera/device_discovery.h>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <fstream>
|
||||
|
||||
namespace {
|
||||
int discovered = 1, opens = 0, closes = 0, freed = 0, writes = 0;
|
||||
@@ -32,7 +33,13 @@ uint32_t PreviewParam::GetCropDstWidth() const { return 1920; }
|
||||
uint32_t PreviewParam::GetCropDstHeight() const { return 960; }
|
||||
int32_t PreviewParam::GetCropOffsetX() const { return 0; }
|
||||
int32_t PreviewParam::GetCropOffsetY() const { return 0; }
|
||||
PreviewParam Camera::GetPreviewParam() const { return PreviewParam(); }
|
||||
PreviewParam Camera::GetPreviewParam() const {
|
||||
PreviewParam p;
|
||||
p.camera_name = "Insta360 X4"; p.encode_type = VideoEncodeType::H264;
|
||||
p.delay_timestamp = 127; p.sweep_time = 391;
|
||||
p.acceleration_range = 16; p.gyro_range = 2000;
|
||||
return p;
|
||||
}
|
||||
|
||||
class ExposureSettingsPrivate {
|
||||
public:
|
||||
@@ -76,6 +83,14 @@ std::vector<std::string> Camera::GetCameraFilesList() const {
|
||||
for (int i = 0; i < 65; ++i) out.push_back("/DCIM/synthetic_" + std::to_string(i) + ".insv");
|
||||
return out;
|
||||
}
|
||||
bool Camera::DownloadCameraFile(const std::string&, const std::string& local, DownloadProgressCallBack progress) const {
|
||||
std::ofstream stream(local, std::ios::binary);
|
||||
stream << "synthetic camera original";
|
||||
stream.close();
|
||||
if (progress) progress(25, 25);
|
||||
return bool(stream);
|
||||
}
|
||||
void Camera::CancelDownload() {}
|
||||
std::vector<DeviceDescriptor> DeviceDiscovery::GetAvailableDevices() {
|
||||
std::vector<DeviceDescriptor> out;
|
||||
for (int i = 0; i < discovered; ++i) out.push_back({CameraType::Insta360X4, "SYNTHETIC-X4", "Insta360 X4", "TEST-FW", {ConnectionType::USB, "Insta360 X4", nullptr}});
|
||||
@@ -139,7 +154,7 @@ void test_recording(int value) { recording = value; if (capture_callback) captur
|
||||
void test_packet(int stream_index, int size, int marker) {
|
||||
if (!delegate) return;
|
||||
std::vector<uint8_t> packet(size, uint8_t(marker));
|
||||
delegate->OnVideoData(packet.data(), packet.size(), 12345, 0, stream_index);
|
||||
delegate->OnVideoData(packet.data(), packet.size(), 12345, 0x20 + stream_index, stream_index);
|
||||
std::fill(packet.begin(), packet.end(), 0); // prove bridge owns copied bytes
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user