feat(app): add ICameraBackend, SubprocessCameraBackend, and SimCameraBackend

This commit is contained in:
2026-11-19 13:57:45 -05:00
parent 97b3e93f98
commit 4304cb259d
7 changed files with 2861 additions and 0 deletions

View File

@@ -35,6 +35,8 @@ add_library(czcamera_core STATIC
src/storage.cpp
src/filters.cpp
src/jpeg_pipeline.cpp
src/subprocess_backend.cpp
src/sim_backend.cpp
)
target_include_directories(czcamera_core
@@ -91,4 +93,12 @@ if(CZ_BUILD_TESTS)
target_compile_options(test_filters_and_jpeg PRIVATE -Wall -Wextra -Wpedantic)
target_link_libraries(test_filters_and_jpeg PRIVATE czcamera_core)
add_test(NAME test_filters_and_jpeg COMMAND test_filters_and_jpeg)
add_executable(test_backend_protocol tests/test_backend_protocol.cpp)
target_compile_options(test_backend_protocol PRIVATE -Wall -Wextra -Wpedantic)
target_compile_definitions(test_backend_protocol PRIVATE
CZ_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}/.."
)
target_link_libraries(test_backend_protocol PRIVATE czcamera_core)
add_test(NAME test_backend_protocol COMMAND test_backend_protocol)
endif()

View File

@@ -0,0 +1,88 @@
#pragma once
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace cz {
struct CameraStreamSpec {
std::string mode = "photo"; // "photo" | "video" | "timelapse"
int main_width = 3280;
int main_height = 2464;
int preview_width = 226;
int preview_height = 170;
int fps = 30;
float zoom = 1.0f;
float ev = 0.0f;
std::string camera_transform = "auto"; // "auto" | "0" | "180" | "hflip" | "vflip"
};
struct PreviewFrame {
uint64_t seq = 0;
int width = 0;
int height = 0;
std::vector<uint8_t> rgb24;
bool is_16_9 = false;
};
struct StillCaptureResult {
bool ok = false;
std::string error;
int width = 0;
int height = 0;
uint64_t bytes = 0;
};
struct VideoSpec {
int width = 1280;
int height = 720;
int fps = 30;
int bitrate_bps = 4000000;
bool audio_enabled = true;
std::string tmp_path;
};
struct VideoStopResult {
bool ok = false;
std::string error;
double duration_sec = 0.0;
uint64_t bytes = 0;
bool audio_recorded = false;
};
struct BackendHealth {
bool ready = false;
bool recording = false;
bool paused = false;
bool audio_warning = false;
std::string last_error;
std::string backend_name;
};
class ICameraBackend {
public:
virtual ~ICameraBackend() = default;
virtual bool start(const CameraStreamSpec& initial_spec,
std::string& out_err) = 0;
virtual void stop() = 0;
virtual bool reconfigure(const CameraStreamSpec& spec,
std::string& out_err) = 0;
virtual bool set_controls(float zoom, float ev, std::string& out_err) = 0;
virtual bool pause(std::string& out_err) = 0;
virtual bool resume(std::string& out_err) = 0;
virtual bool copy_latest_preview(uint64_t last_seen_seq,
PreviewFrame& out_frame) = 0;
virtual StillCaptureResult capture_still(const std::string& tmp_jpeg_path,
int width,
int height) = 0;
virtual bool start_video(const VideoSpec& spec, std::string& out_err) = 0;
virtual VideoStopResult stop_video() = 0;
virtual BackendHealth status() const = 0;
};
std::unique_ptr<ICameraBackend> create_camera_backend(bool force_mock = false);
} // namespace cz

641
app/src/sim_backend.cpp Normal file
View File

@@ -0,0 +1,641 @@
#include "sim_backend.hpp"
#include "jpeg_pipeline.hpp"
#include "subprocess_backend.hpp"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
namespace cz {
namespace {
std::string to_lower_ascii(std::string s) {
for (char& c : s) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return s;
}
bool is_16_9_spec(const CameraStreamSpec& spec) {
if (spec.mode == "video") {
return true;
}
if (spec.main_height > 0) {
const double aspect =
static_cast<double>(spec.main_width) /
static_cast<double>(spec.main_height);
if (std::abs(aspect - (16.0 / 9.0)) < 0.05) {
return true;
}
}
return false;
}
uint8_t clamp_u8(float v) {
if (v <= 0.0f) return 0;
if (v >= 255.0f) return 255;
return static_cast<uint8_t>(std::lround(v));
}
void render_procedural_scene_rgb24(int width,
int height,
uint64_t tick,
float zoom,
float ev,
const std::string& transform,
std::vector<uint8_t>& out_rgb24) {
const int w = std::max(2, width);
const int h = std::max(2, height);
out_rgb24.resize(static_cast<size_t>(w) * static_cast<size_t>(h) * 3u);
const float z = std::clamp(zoom, 1.0f, 4.0f);
const float inv_z = 1.0f / z;
const float ev_clamped = std::clamp(ev, -2.0f, 2.0f);
const float ev_gain = std::pow(2.0f, ev_clamped * 0.45f);
const float ev_bias = ev_clamped * 16.0f;
const std::string tf = to_lower_ascii(transform);
const bool flip_x = (tf == "180" || tf == "hflip");
const bool flip_y = (tf == "180" || tf == "vflip");
// Animated sun position
const float phase = static_cast<float>(tick % 240u) / 240.0f;
const float sun_u = 0.22f + 0.56f * phase;
const float sun_v = 0.28f - 0.08f * std::sin(phase * 3.14159265f);
const float sun_r2 = 0.0045f;
// Precompute column-wise mountain ridges to keep 8MP rendering fast
std::vector<float> col_u(static_cast<size_t>(w));
std::vector<float> far_ridge(static_cast<size_t>(w));
std::vector<float> near_ridge(static_cast<size_t>(w));
for (int x = 0; x < w; ++x) {
const float raw_u =
(static_cast<float>(x) + 0.5f) / static_cast<float>(w);
const float u_t = flip_x ? (1.0f - raw_u) : raw_u;
const float u = 0.5f + (u_t - 0.5f) * inv_z;
col_u[static_cast<size_t>(x)] = u;
far_ridge[static_cast<size_t>(x)] =
0.54f - 0.09f * std::sin(u * 9.0f + 0.4f) -
0.04f * std::cos(u * 21.0f);
near_ridge[static_cast<size_t>(x)] =
0.66f - 0.07f * std::sin(u * 13.0f + 2.1f) -
0.03f * std::sin(u * 29.0f);
}
for (int y = 0; y < h; ++y) {
const float raw_v =
(static_cast<float>(y) + 0.5f) / static_cast<float>(h);
const float v_t = flip_y ? (1.0f - raw_v) : raw_v;
const float v = 0.5f + (v_t - 0.5f) * inv_z;
const float dv_sun = v - sun_v;
uint8_t* row = out_rgb24.data() + static_cast<size_t>(y) * w * 3u;
// Sky vertical gradient terms
const float sky_t = std::clamp(v / 0.72f, 0.0f, 1.0f);
const float sky_r = 28.0f + 168.0f * sky_t;
const float sky_g = 54.0f + 112.0f * sky_t;
const float sky_b = 112.0f + 46.0f * sky_t;
const float wave =
10.0f * std::sin(v * 80.0f - static_cast<float>(tick) * 0.25f);
for (int x = 0; x < w; ++x) {
const size_t sx = static_cast<size_t>(x);
const float u = col_u[sx];
float r = 0.0f;
float g = 0.0f;
float b = 0.0f;
if (v >= 0.72f) {
// Foreground lake + shimmer reflection
const float depth = (v - 0.72f) / 0.28f;
r = 22.0f + 18.0f * (1.0f - depth);
g = 48.0f + 26.0f * (1.0f - depth);
b = 76.0f + 28.0f * (1.0f - depth);
const float sun_glint = std::exp(-((u - sun_u) * (u - sun_u)) * 90.0f);
if (sun_glint > 0.08f) {
const float shimmer = std::max(0.0f, wave) * sun_glint;
r += 8.0f * shimmer;
g += 5.5f * shimmer;
b += 2.5f * shimmer;
}
} else if (v >= near_ridge[sx]) {
// Near dark pine ridge
r = 26.0f;
g = 46.0f;
b = 38.0f;
} else if (v >= far_ridge[sx]) {
// Far atmospheric mountain ridge
r = 68.0f;
g = 78.0f;
b = 104.0f;
} else {
// Sky + sun disc
r = sky_r;
g = sky_g;
b = sky_b;
const float du = (u - sun_u) * 1.33f; // circular in 4:3 aspect
const float d2 = du * du + dv_sun * dv_sun;
if (d2 < sun_r2) {
r = 250.0f;
g = 228.0f;
b = 152.0f;
} else if (d2 < sun_r2 * 5.0f) {
const float halo = 1.0f - (d2 - sun_r2) / (sun_r2 * 4.0f);
r += 55.0f * halo;
g += 40.0f * halo;
b += 15.0f * halo;
}
}
row[x * 3 + 0] = clamp_u8(r * ev_gain + ev_bias);
row[x * 3 + 1] = clamp_u8(g * ev_gain + ev_bias);
row[x * 3 + 2] = clamp_u8(b * ev_gain + ev_bias);
}
}
}
bool write_minimal_mp4_stub(const std::string& path, std::string& out_err) {
static constexpr uint8_t kStub[] = {
0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'm', 'p', '4', '2',
0x00, 0x00, 0x00, 0x00, 'm', 'p', '4', '2', 'i', 's', 'o', 'm',
0x00, 0x00, 0x00, 0x08, 'f', 'r', 'e', 'e',
0x00, 0x00, 0x00, 0x10, 'm', 'd', 'a', 't', 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
FILE* fp = std::fopen(path.c_str(), "wb");
if (!fp) {
out_err = "failed to write MP4 stub '" + path + "': " +
std::strerror(errno);
return false;
}
const size_t written = std::fwrite(kStub, 1, sizeof(kStub), fp);
std::fflush(fp);
std::fclose(fp);
if (written != sizeof(kStub)) {
out_err = "short write on MP4 stub";
return false;
}
return true;
}
bool try_write_ffmpeg_mp4(const VideoSpec& spec, double duration_sec) {
const double clamped_dur = std::clamp(duration_sec, 0.2, 3.0);
const int w = std::max(64, std::min(640, spec.width & ~1));
const int h = std::max(64, std::min(360, spec.height & ~1));
const int fps = std::clamp(spec.fps, 10, 30);
char dur_buf[32];
std::snprintf(dur_buf, sizeof(dur_buf), "%.2f", clamped_dur);
const std::string vsrc = "testsrc=duration=" + std::string(dur_buf) +
":size=" + std::to_string(w) + "x" +
std::to_string(h) + ":rate=" + std::to_string(fps);
const std::string asrc =
"anullsrc=channel_layout=mono:sample_rate=44100";
std::vector<std::string> args = {
"ffmpeg", "-nostdin", "-loglevel", "error", "-y", "-f", "lavfi", "-i",
vsrc};
if (spec.audio_enabled) {
args.push_back("-f");
args.push_back("lavfi");
args.push_back("-i");
args.push_back(asrc);
args.push_back("-shortest");
}
args.push_back("-c:v");
args.push_back("libx264");
args.push_back("-preset");
args.push_back("ultrafast");
args.push_back("-pix_fmt");
args.push_back("yuv420p");
if (spec.audio_enabled) {
args.push_back("-c:a");
args.push_back("aac");
args.push_back("-b:a");
args.push_back("64k");
}
args.push_back("-f");
args.push_back("mp4");
args.push_back("-movflags");
args.push_back("+faststart");
args.push_back(spec.tmp_path);
std::vector<char*> argv_ptrs;
argv_ptrs.reserve(args.size() + 1);
for (auto& a : args) {
argv_ptrs.push_back(const_cast<char*>(a.c_str()));
}
argv_ptrs.push_back(nullptr);
const pid_t pid = ::fork();
if (pid < 0) {
return false;
}
if (pid == 0) {
const int devnull = ::open("/dev/null", O_RDWR);
if (devnull >= 0) {
::dup2(devnull, STDIN_FILENO);
::dup2(devnull, STDOUT_FILENO);
::dup2(devnull, STDERR_FILENO);
if (devnull > 2) ::close(devnull);
}
::execvp("ffmpeg", argv_ptrs.data());
_exit(127);
}
// Wait up to 4 seconds for short synthetic MP4 encode.
const auto dl =
std::chrono::steady_clock::now() + std::chrono::seconds(4);
int st = 0;
pid_t r = 0;
while ((r = ::waitpid(pid, &st, WNOHANG)) == 0 &&
std::chrono::steady_clock::now() < dl) {
std::this_thread::sleep_for(std::chrono::milliseconds(15));
}
if (r == 0) {
::kill(pid, SIGKILL);
while (::waitpid(pid, &st, 0) < 0 && errno == EINTR) {
}
return false;
}
if (r != pid || !WIFEXITED(st) || WEXITSTATUS(st) != 0) {
return false;
}
struct stat fst {};
return ::stat(spec.tmp_path.c_str(), &fst) == 0 && fst.st_size > 0;
}
} // namespace
SimCameraBackend::~SimCameraBackend() { stop(); }
void SimCameraBackend::publish_frame_locked_state(uint64_t tick,
const CameraStreamSpec& spec,
bool is_16_9) {
const int pw = std::max(2, spec.preview_width & ~1);
const int ph = std::max(2, spec.preview_height & ~1);
std::vector<uint8_t> rgb;
render_procedural_scene_rgb24(pw, ph, tick, spec.zoom, spec.ev,
spec.camera_transform, rgb);
std::lock_guard<std::mutex> fr_lock(frame_mutex_);
latest_frame_.seq = ++seq_counter_;
latest_frame_.width = pw;
latest_frame_.height = ph;
latest_frame_.is_16_9 = is_16_9;
latest_frame_.rgb24 = std::move(rgb);
}
bool SimCameraBackend::start(const CameraStreamSpec& initial_spec,
std::string& out_err) {
stop();
out_err.clear();
CameraStreamSpec norm = initial_spec;
if (norm.mode.empty()) norm.mode = "photo";
if (norm.camera_transform.empty()) norm.camera_transform = "auto";
norm.zoom = std::clamp(norm.zoom, 1.0f, 4.0f);
norm.ev = std::clamp(norm.ev, -2.0f, 2.0f);
norm.fps = std::clamp(norm.fps, 1, 60);
uint64_t initial_tick = 0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
spec_ = norm;
running_ = true;
ready_ = true;
paused_ = false;
recording_ = false;
stop_thread_ = false;
last_error_.clear();
initial_tick = tick_++;
}
publish_frame_locked_state(initial_tick, norm, is_16_9_spec(norm));
render_thread_ = std::thread(&SimCameraBackend::render_loop, this);
return true;
}
void SimCameraBackend::stop() {
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!running_ && !render_thread_.joinable()) {
ready_ = false;
recording_ = false;
paused_ = false;
return;
}
stop_thread_ = true;
running_ = false;
ready_ = false;
recording_ = false;
paused_ = false;
state_cv_.notify_all();
}
if (render_thread_.joinable()) {
render_thread_.join();
}
}
void SimCameraBackend::render_loop() {
while (true) {
CameraStreamSpec snap_spec;
uint64_t snap_tick = 0;
{
std::unique_lock<std::mutex> lock(state_mutex_);
if (stop_thread_) {
return;
}
if (paused_ || !ready_) {
state_cv_.wait(lock,
[&]() { return stop_thread_ || (!paused_ && ready_); });
if (stop_thread_) {
return;
}
}
snap_spec = spec_;
snap_tick = tick_++;
}
publish_frame_locked_state(snap_tick, snap_spec, is_16_9_spec(snap_spec));
const int fps = std::clamp(snap_spec.fps, 1, 60);
const auto period = std::chrono::milliseconds(1000 / fps);
std::unique_lock<std::mutex> lock(state_mutex_);
state_cv_.wait_for(lock, period, [&]() { return stop_thread_; });
if (stop_thread_) {
return;
}
}
}
bool SimCameraBackend::reconfigure(const CameraStreamSpec& spec,
std::string& out_err) {
out_err.clear();
CameraStreamSpec norm = spec;
if (norm.mode.empty()) norm.mode = "photo";
if (norm.camera_transform.empty()) norm.camera_transform = "auto";
norm.zoom = std::clamp(norm.zoom, 1.0f, 4.0f);
norm.ev = std::clamp(norm.ev, -2.0f, 2.0f);
norm.fps = std::clamp(norm.fps, 1, 60);
uint64_t cur_tick = 0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!ready_) {
out_err = "sim camera backend not started";
return false;
}
if (recording_) {
out_err = "camera_recording";
return false;
}
spec_ = norm;
paused_ = false;
cur_tick = tick_++;
state_cv_.notify_all();
}
publish_frame_locked_state(cur_tick, norm, is_16_9_spec(norm));
return true;
}
bool SimCameraBackend::set_controls(float zoom,
float ev,
std::string& out_err) {
out_err.clear();
CameraStreamSpec snap;
uint64_t cur_tick = 0;
bool should_publish = false;
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!ready_) {
out_err = "sim camera backend not started";
return false;
}
spec_.zoom = std::clamp(zoom, 1.0f, 4.0f);
spec_.ev = std::clamp(ev, -2.0f, 2.0f);
snap = spec_;
cur_tick = tick_++;
should_publish = !paused_;
}
if (should_publish) {
publish_frame_locked_state(cur_tick, snap, is_16_9_spec(snap));
}
return true;
}
bool SimCameraBackend::pause(std::string& out_err) {
out_err.clear();
std::lock_guard<std::mutex> lock(state_mutex_);
if (!ready_) {
out_err = "sim camera backend not started";
return false;
}
recording_ = false;
paused_ = true;
state_cv_.notify_all();
return true;
}
bool SimCameraBackend::resume(std::string& out_err) {
out_err.clear();
CameraStreamSpec snap;
uint64_t cur_tick = 0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!ready_) {
out_err = "sim camera backend not started";
return false;
}
paused_ = false;
snap = spec_;
cur_tick = tick_++;
state_cv_.notify_all();
}
publish_frame_locked_state(cur_tick, snap, is_16_9_spec(snap));
return true;
}
bool SimCameraBackend::copy_latest_preview(uint64_t last_seen_seq,
PreviewFrame& out_frame) {
std::lock_guard<std::mutex> fr_lock(frame_mutex_);
if (latest_frame_.seq == 0 || latest_frame_.seq <= last_seen_seq) {
return false;
}
out_frame = latest_frame_;
return true;
}
StillCaptureResult SimCameraBackend::capture_still(
const std::string& tmp_jpeg_path,
int width,
int height) {
StillCaptureResult res;
if (tmp_jpeg_path.empty() || width <= 0 || height <= 0) {
res.error = "invalid capture_still arguments";
return res;
}
CameraStreamSpec snap;
uint64_t cur_tick = 0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!ready_ || paused_) {
res.error = "camera_not_started";
return res;
}
if (recording_) {
res.error = "camera_busy";
return res;
}
snap = spec_;
cur_tick = tick_;
}
const int req_w = std::max(2, width & ~1);
const int req_h = std::max(2, height & ~1);
std::vector<uint8_t> rgb;
render_procedural_scene_rgb24(req_w, req_h, cur_tick, snap.zoom, snap.ev,
snap.camera_transform, rgb);
if (!encode_jpeg_rgb24(tmp_jpeg_path, rgb.data(), req_w, req_h, 90,
res.error)) {
return res;
}
struct stat st {};
if (::stat(tmp_jpeg_path.c_str(), &st) != 0) {
res.error = "failed to stat captured JPEG";
return res;
}
res.ok = true;
res.width = req_w;
res.height = req_h;
res.bytes = static_cast<uint64_t>(st.st_size);
return res;
}
bool SimCameraBackend::start_video(const VideoSpec& spec,
std::string& out_err) {
out_err.clear();
if (spec.tmp_path.empty() || spec.width <= 0 || spec.height <= 0 ||
spec.fps <= 0) {
out_err = "invalid start_video specification";
return false;
}
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!ready_ || paused_) {
out_err = "camera_not_started";
return false;
}
if (recording_) {
out_err = "already_recording";
return false;
}
if (!write_minimal_mp4_stub(spec.tmp_path, out_err)) {
return false;
}
active_video_ = spec;
video_start_time_ = std::chrono::steady_clock::now();
recording_ = true;
spec_.mode = "video";
}
return true;
}
VideoStopResult SimCameraBackend::stop_video() {
VideoStopResult res;
VideoSpec spec;
std::chrono::steady_clock::time_point t0;
{
std::lock_guard<std::mutex> lock(state_mutex_);
if (!recording_) {
res.error = "not_recording";
return res;
}
spec = active_video_;
t0 = video_start_time_;
recording_ = false;
active_video_ = VideoSpec{};
}
const auto elapsed = std::chrono::duration<double>(
std::chrono::steady_clock::now() - t0)
.count();
const double duration_sec = std::max(0.001, elapsed);
if (!try_write_ffmpeg_mp4(spec, duration_sec)) {
if (!write_minimal_mp4_stub(spec.tmp_path, res.error)) {
return res;
}
}
struct stat st {};
if (::stat(spec.tmp_path.c_str(), &st) != 0 || st.st_size <= 0) {
res.error = "video staging file missing or empty";
return res;
}
res.ok = true;
res.duration_sec = duration_sec;
res.bytes = static_cast<uint64_t>(st.st_size);
res.audio_recorded = spec.audio_enabled;
return res;
}
BackendHealth SimCameraBackend::status() const {
std::lock_guard<std::mutex> lock(state_mutex_);
BackendHealth h;
h.ready = ready_;
h.recording = recording_;
h.paused = paused_;
h.audio_warning = false;
h.last_error = last_error_;
h.backend_name = "sim";
return h;
}
std::unique_ptr<ICameraBackend> create_camera_backend(bool force_mock) {
if (force_mock) {
return std::make_unique<SimCameraBackend>();
}
const char* env_backend = std::getenv("CZCAMERA_BACKEND");
if (env_backend && *env_backend) {
const std::string val = to_lower_ascii(env_backend);
if (val == "sim" || val == "mock") {
return std::make_unique<SimCameraBackend>();
}
if (val == "subprocess") {
return std::make_unique<SubprocessCameraBackend>();
}
}
const char* env_bin = std::getenv("CZCAMERA_CAM_BIN");
if (env_bin && *env_bin) {
return std::make_unique<SubprocessCameraBackend>();
}
#ifdef CZ_TARGET_DEVICE
return std::make_unique<SubprocessCameraBackend>();
#else
return std::make_unique<SimCameraBackend>();
#endif
}
} // namespace cz

71
app/src/sim_backend.hpp Normal file
View File

@@ -0,0 +1,71 @@
#pragma once
#include "camera_backend.hpp"
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
namespace cz {
class SimCameraBackend final : public ICameraBackend {
public:
SimCameraBackend() = default;
~SimCameraBackend() override;
SimCameraBackend(const SimCameraBackend&) = delete;
SimCameraBackend& operator=(const SimCameraBackend&) = delete;
SimCameraBackend(SimCameraBackend&&) = delete;
SimCameraBackend& operator=(SimCameraBackend&&) = delete;
bool start(const CameraStreamSpec& initial_spec,
std::string& out_err) override;
void stop() override;
bool reconfigure(const CameraStreamSpec& spec,
std::string& out_err) override;
bool set_controls(float zoom, float ev, std::string& out_err) override;
bool pause(std::string& out_err) override;
bool resume(std::string& out_err) override;
bool copy_latest_preview(uint64_t last_seen_seq,
PreviewFrame& out_frame) override;
StillCaptureResult capture_still(const std::string& tmp_jpeg_path,
int width,
int height) override;
bool start_video(const VideoSpec& spec, std::string& out_err) override;
VideoStopResult stop_video() override;
BackendHealth status() const override;
private:
void render_loop();
void publish_frame_locked_state(uint64_t tick,
const CameraStreamSpec& spec,
bool is_16_9);
mutable std::mutex state_mutex_;
std::condition_variable state_cv_;
bool running_ = false;
bool ready_ = false;
bool recording_ = false;
bool paused_ = false;
bool stop_thread_ = false;
std::string last_error_;
CameraStreamSpec spec_;
uint64_t tick_ = 0;
VideoSpec active_video_;
std::chrono::steady_clock::time_point video_start_time_;
std::mutex frame_mutex_;
PreviewFrame latest_frame_;
uint64_t seq_counter_ = 0;
std::thread render_thread_;
};
} // namespace cz

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,142 @@
#pragma once
#include "camera_backend.hpp"
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <map>
#include <mutex>
#include <string>
#include <sys/types.h>
#include <thread>
#include <vector>
namespace cz {
inline constexpr size_t kCzfrHeaderBytes = 16;
inline constexpr uint8_t kCzfrPixfmtYuv420 = 1;
inline constexpr uint8_t kCzfrPixfmtRgb24 = 2;
inline constexpr uint8_t kCzfrFlagAspect16_9 = 0x01;
inline constexpr uint32_t kCzfrMaxPayloadBytes = 16u * 1024u * 1024u;
bool parse_czfr_header(const uint8_t* hdr16,
uint16_t& w,
uint16_t& h,
uint8_t& pixfmt,
uint8_t& flags,
uint32_t& payload_bytes);
bool yuv420_to_rgb24(const uint8_t* yuv,
int width,
int height,
std::vector<uint8_t>& out_rgb24);
namespace json_detail {
struct JsonValue;
}
class SubprocessCameraBackend final : public ICameraBackend {
public:
explicit SubprocessCameraBackend(std::string cam_bin_path = "",
std::vector<std::string> extra_args = {});
~SubprocessCameraBackend() override;
SubprocessCameraBackend(const SubprocessCameraBackend&) = delete;
SubprocessCameraBackend& operator=(const SubprocessCameraBackend&) = delete;
SubprocessCameraBackend(SubprocessCameraBackend&&) = delete;
SubprocessCameraBackend& operator=(SubprocessCameraBackend&&) = delete;
bool start(const CameraStreamSpec& initial_spec,
std::string& out_err) override;
void stop() override;
bool reconfigure(const CameraStreamSpec& spec,
std::string& out_err) override;
bool set_controls(float zoom, float ev, std::string& out_err) override;
bool pause(std::string& out_err) override;
bool resume(std::string& out_err) override;
bool copy_latest_preview(uint64_t last_seen_seq,
PreviewFrame& out_frame) override;
StillCaptureResult capture_still(const std::string& tmp_jpeg_path,
int width,
int height) override;
bool start_video(const VideoSpec& spec, std::string& out_err) override;
VideoStopResult stop_video() override;
BackendHealth status() const override;
pid_t child_pid() const;
private:
struct RawFrameSlot {
uint64_t seq = 0;
uint16_t width = 0;
uint16_t height = 0;
uint8_t pixfmt = 0;
uint8_t flags = 0;
std::vector<uint8_t> payload;
};
std::string resolve_bin_path() const;
bool send_configure(const CameraStreamSpec& spec,
std::string& out_err,
bool allow_before_ready = false);
bool send_command(const std::string& cmd_name,
const std::string& json_body_without_braces,
int timeout_ms,
std::map<std::string, json_detail::JsonValue>& out_reply,
std::string& out_err,
bool allow_before_ready = false);
void stdout_reader_loop(int stdout_fd, int wake_fd, pid_t pid);
void frame_reader_loop(int frame_fd, int wake_fd);
void handle_stdout_line(const std::string& line);
void stop_locked();
void close_stdin_fd();
void cleanup_fds();
std::string cam_bin_path_;
std::vector<std::string> extra_args_;
std::mutex lifecycle_mutex_;
std::mutex cmd_mutex_;
std::mutex write_mutex_;
std::mutex reap_mutex_;
mutable std::mutex state_mutex_;
std::condition_variable reply_cv_;
pid_t child_pid_ = -1;
int stdin_write_fd_ = -1;
int stdout_read_fd_ = -1;
int frame_read_fd_ = -1;
int wake_read_fd_ = -1;
int wake_write_fd_ = -1;
bool child_running_ = false;
bool ready_ = false;
bool recording_ = false;
bool paused_ = false;
bool audio_warning_ = false;
bool stopping_ = false;
bool process_dead_ = false;
std::string last_error_;
std::string backend_name_ = "picamera2-subprocess";
bool ready_received_ = false;
bool ready_ok_ = false;
std::string ready_error_;
uint64_t next_cmd_id_ = 1;
uint64_t pending_cmd_id_ = 0;
bool pending_reply_ready_ = false;
std::map<std::string, json_detail::JsonValue> pending_reply_;
CameraStreamSpec current_spec_;
std::mutex frame_mutex_;
RawFrameSlot latest_raw_;
uint64_t frame_seq_counter_ = 0;
std::thread stdout_thread_;
std::thread frame_thread_;
};
} // namespace cz

View File

@@ -0,0 +1,699 @@
#include "camera_backend.hpp"
#include "jpeg_pipeline.hpp"
#include "sim_backend.hpp"
#include "subprocess_backend.hpp"
#include <array>
#include <cassert>
#include <cerrno>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
#include <vector>
namespace fs = std::filesystem;
namespace {
struct TempDir {
std::string path;
explicit TempDir(const std::string& name) {
const std::string base =
"/tmp/czcamera_test_" + name + "_" + std::to_string(::getpid());
std::error_code ec;
fs::remove_all(base, ec);
fs::create_directories(base, ec);
assert(!ec);
path = base;
}
~TempDir() {
std::error_code ec;
fs::remove_all(path, ec);
}
};
struct EnvVarGuard {
std::string key;
bool had_old = false;
std::string old_val;
EnvVarGuard(const std::string& k, const std::string& v) : key(k) {
const char* prev = std::getenv(key.c_str());
if (prev != nullptr) {
had_old = true;
old_val = prev;
}
::setenv(key.c_str(), v.c_str(), 1);
}
explicit EnvVarGuard(const std::string& k) : key(k) {
const char* prev = std::getenv(key.c_str());
if (prev != nullptr) {
had_old = true;
old_val = prev;
}
::unsetenv(key.c_str());
}
~EnvVarGuard() {
if (had_old) {
::setenv(key.c_str(), old_val.c_str(), 1);
} else {
::unsetenv(key.c_str());
}
}
};
std::array<uint8_t, 16> pack_header(const char magic[4],
uint16_t w,
uint16_t h,
uint8_t pixfmt,
uint8_t flags,
uint16_t reserved,
uint32_t payload_bytes) {
std::array<uint8_t, 16> hdr{};
std::memcpy(hdr.data(), magic, 4);
hdr[4] = static_cast<uint8_t>(w & 0xFFu);
hdr[5] = static_cast<uint8_t>((w >> 8) & 0xFFu);
hdr[6] = static_cast<uint8_t>(h & 0xFFu);
hdr[7] = static_cast<uint8_t>((h >> 8) & 0xFFu);
hdr[8] = pixfmt;
hdr[9] = flags;
hdr[10] = static_cast<uint8_t>(reserved & 0xFFu);
hdr[11] = static_cast<uint8_t>((reserved >> 8) & 0xFFu);
hdr[12] = static_cast<uint8_t>(payload_bytes & 0xFFu);
hdr[13] = static_cast<uint8_t>((payload_bytes >> 8) & 0xFFu);
hdr[14] = static_cast<uint8_t>((payload_bytes >> 16) & 0xFFu);
hdr[15] = static_cast<uint8_t>((payload_bytes >> 24) & 0xFFu);
return hdr;
}
double mean_luma(const std::vector<uint8_t>& rgb24) {
if (rgb24.empty()) return 0.0;
double sum = 0.0;
const size_t pixels = rgb24.size() / 3;
for (size_t i = 0; i < pixels; ++i) {
sum += 0.299 * rgb24[i * 3 + 0] + 0.587 * rgb24[i * 3 + 1] +
0.114 * rgb24[i * 3 + 2];
}
return sum / static_cast<double>(pixels);
}
bool wait_for_preview_frame(cz::ICameraBackend& backend,
uint64_t after_seq,
cz::PreviewFrame& out,
int timeout_ms = 3000) {
const auto deadline = std::chrono::steady_clock::now() +
std::chrono::milliseconds(timeout_ms);
while (std::chrono::steady_clock::now() < deadline) {
if (backend.copy_latest_preview(after_seq, out)) {
return true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return false;
}
void test_czfr_header_and_yuv420_to_rgb24() {
uint16_t w = 0;
uint16_t h = 0;
uint8_t pixfmt = 0;
uint8_t flags = 0;
uint32_t payload = 0;
// Valid YUV420 226x170 header
const uint32_t yuv_len = 226u * 170u * 3u / 2u;
const auto valid_hdr = pack_header("CZFR", 226, 170, 1, 0, 0, yuv_len);
assert(cz::parse_czfr_header(valid_hdr.data(), w, h, pixfmt, flags, payload));
assert(w == 226 && h == 170 && pixfmt == 1 && flags == 0 &&
payload == yuv_len);
// Valid RGB24 16:9 header at exact 16 MiB boundary
const uint32_t max_ok = 16u * 1024u * 1024u;
const auto max_hdr = pack_header("CZFR", 226, 128, 2, 1, 0, max_ok);
assert(cz::parse_czfr_header(max_hdr.data(), w, h, pixfmt, flags, payload));
assert(w == 226 && h == 128 && pixfmt == 2 && flags == 1 &&
payload == max_ok);
// Reject nullptr, bad magic, zero dims, invalid pixfmt, zero payload, >16 MiB
assert(!cz::parse_czfr_header(nullptr, w, h, pixfmt, flags, payload));
const auto bad_magic = pack_header("BAD!", 226, 170, 1, 0, 0, yuv_len);
assert(!cz::parse_czfr_header(bad_magic.data(), w, h, pixfmt, flags, payload));
const auto zero_w = pack_header("CZFR", 0, 170, 1, 0, 0, yuv_len);
assert(!cz::parse_czfr_header(zero_w.data(), w, h, pixfmt, flags, payload));
const auto bad_fmt = pack_header("CZFR", 226, 170, 9, 0, 0, yuv_len);
assert(!cz::parse_czfr_header(bad_fmt.data(), w, h, pixfmt, flags, payload));
const auto zero_len = pack_header("CZFR", 226, 170, 1, 0, 0, 0);
assert(!cz::parse_czfr_header(zero_len.data(), w, h, pixfmt, flags, payload));
const auto oversized = pack_header("CZFR", 226, 170, 1, 0, 0, max_ok + 1u);
assert(!cz::parse_czfr_header(oversized.data(), w, h, pixfmt, flags, payload));
// YUV420 -> RGB24 validation and BT.601 color accuracy
std::vector<uint8_t> rgb;
assert(!cz::yuv420_to_rgb24(nullptr, 4, 4, rgb));
std::vector<uint8_t> dummy(16, 0);
assert(!cz::yuv420_to_rgb24(dummy.data(), 0, 4, rgb));
assert(!cz::yuv420_to_rgb24(dummy.data(), 3, 4, rgb));
assert(!cz::yuv420_to_rgb24(dummy.data(), 4, 3, rgb));
// 4x4 YUV420 image with 4 distinct 2x2 quadrants:
// Top-left: Black (Y=16, U=128, V=128) -> (0, 0, 0)
// Top-right: White (Y=235, U=128, V=128) -> (255, 255, 255)
// Bottom-left: Red (Y=81, U=90, V=240) -> (~255, ~0, ~0)
// Bottom-right: Blue (Y=41, U=240, V=110) -> (~0, ~0, ~255)
// Plus test Green separately.
std::vector<uint8_t> yuv(4 * 4 * 3 / 2, 0);
// Y plane (4x4)
for (int row = 0; row < 4; ++row) {
for (int col = 0; col < 4; ++col) {
uint8_t y_val = 16;
if (row < 2 && col < 2) y_val = 16;
else if (row < 2 && col >= 2) y_val = 235;
else if (row >= 2 && col < 2) y_val = 81;
else y_val = 41;
yuv[static_cast<size_t>(row * 4 + col)] = y_val;
}
}
// U plane (2x2 at offset 16): TL=128, TR=128, BL=90, BR=240
yuv[16] = 128;
yuv[17] = 128;
yuv[18] = 90;
yuv[19] = 240;
// V plane (2x2 at offset 20): TL=128, TR=128, BL=240, BR=110
yuv[20] = 128;
yuv[21] = 128;
yuv[22] = 240;
yuv[23] = 110;
assert(cz::yuv420_to_rgb24(yuv.data(), 4, 4, rgb));
assert(rgb.size() == 4u * 4u * 3u);
auto px = [&](int x, int y) -> std::array<uint8_t, 3> {
const size_t idx = static_cast<size_t>(y * 4 + x) * 3u;
return {rgb[idx], rgb[idx + 1], rgb[idx + 2]};
};
// Black (TL)
for (int y = 0; y < 2; ++y) {
for (int x = 0; x < 2; ++x) {
auto c = px(x, y);
assert(c[0] <= 2 && c[1] <= 2 && c[2] <= 2);
}
}
// White (TR)
for (int y = 0; y < 2; ++y) {
for (int x = 2; x < 4; ++x) {
auto c = px(x, y);
assert(c[0] >= 253 && c[1] >= 253 && c[2] >= 253);
}
}
// Red (BL)
for (int y = 2; y < 4; ++y) {
for (int x = 0; x < 2; ++x) {
auto c = px(x, y);
assert(c[0] >= 248 && c[1] <= 8 && c[2] <= 8);
}
}
// Blue (BR)
for (int y = 2; y < 4; ++y) {
for (int x = 2; x < 4; ++x) {
auto c = px(x, y);
assert(c[0] <= 8 && c[1] <= 8 && c[2] >= 248);
}
}
// Pure green 2x2 block: Y=145, U=54, V=34
std::vector<uint8_t> green_yuv = {145, 145, 145, 145, 54, 34};
assert(cz::yuv420_to_rgb24(green_yuv.data(), 2, 2, rgb));
assert(rgb.size() == 12);
assert(rgb[0] <= 8 && rgb[1] >= 248 && rgb[2] <= 8);
}
void test_sim_backend_lifecycle() {
TempDir tmp("sim_backend");
// Factory selection tests
{
auto forced = cz::create_camera_backend(true);
assert(forced != nullptr);
assert(forced->status().backend_name == "sim");
EnvVarGuard env_b("CZCAMERA_BACKEND", "sim");
auto from_env = cz::create_camera_backend(false);
assert(from_env != nullptr);
assert(from_env->status().backend_name == "sim");
}
cz::SimCameraBackend sim;
assert(!sim.status().ready);
assert(sim.status().backend_name == "sim");
cz::CameraStreamSpec spec;
spec.mode = "photo";
spec.main_width = 640;
spec.main_height = 480;
spec.preview_width = 226;
spec.preview_height = 170;
spec.fps = 30;
spec.zoom = 1.0f;
spec.ev = 0.0f;
spec.camera_transform = "auto";
std::string err;
assert(sim.start(spec, err));
assert(err.empty());
assert(sim.status().ready);
assert(!sim.status().paused);
assert(!sim.status().recording);
cz::PreviewFrame f1;
assert(wait_for_preview_frame(sim, 0, f1));
assert(f1.seq >= 1);
assert(f1.width == 226 && f1.height == 170);
assert(f1.rgb24.size() == 226u * 170u * 3u);
// Next frame should arrive with higher sequence number
cz::PreviewFrame f2;
assert(wait_for_preview_frame(sim, f1.seq, f2));
assert(f2.seq > f1.seq);
assert(!sim.copy_latest_preview(f2.seq, f2));
// EV and zoom controls visibly affect frame brightness/content
assert(sim.set_controls(1.0f, -2.0f, err));
cz::PreviewFrame dark_frame;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
assert(wait_for_preview_frame(sim, f2.seq, dark_frame));
assert(sim.set_controls(3.0f, 2.0f, err));
cz::PreviewFrame bright_frame;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
assert(wait_for_preview_frame(sim, dark_frame.seq, bright_frame));
assert(mean_luma(bright_frame.rgb24) > mean_luma(dark_frame.rgb24) + 15.0);
// Transform flip ("180") flips sky (top) and lake (bottom) vertically
cz::CameraStreamSpec normal_spec = spec;
normal_spec.camera_transform = "0";
assert(sim.reconfigure(normal_spec, err));
cz::PreviewFrame norm_f;
assert(wait_for_preview_frame(sim, bright_frame.seq, norm_f));
const double norm_top_b = norm_f.rgb24[2]; // sky blue at (0,0)
const double norm_bot_b =
norm_f.rgb24[(static_cast<size_t>(norm_f.height - 1) * norm_f.width) * 3 + 2];
cz::CameraStreamSpec flip_spec = spec;
flip_spec.camera_transform = "180";
assert(sim.reconfigure(flip_spec, err));
cz::PreviewFrame flip_f;
assert(wait_for_preview_frame(sim, norm_f.seq, flip_f));
const double flip_top_b = flip_f.rgb24[2];
const double flip_bot_b =
flip_f.rgb24[(static_cast<size_t>(flip_f.height - 1) * flip_f.width) * 3 + 2];
assert(norm_top_b != flip_top_b || norm_bot_b != flip_bot_b);
assert(std::abs(norm_top_b - flip_bot_b) < 2.0);
// Still capture writes a valid JPEG
const std::string jpg_tmp = tmp.path + "/.IMG_test.jpg.tmp";
cz::StillCaptureResult still = sim.capture_still(jpg_tmp, 640, 480);
assert(still.ok);
assert(still.width == 640 && still.height == 480);
assert(still.bytes > 0);
cz::RgbImage decoded;
assert(cz::decode_jpeg_rgb24(jpg_tmp, decoded, err));
assert(decoded.width == 640 && decoded.height == 480);
// Pause & resume toggle paused state
assert(sim.pause(err));
assert(sim.status().paused);
assert(sim.resume(err));
assert(!sim.status().paused);
// Video start/stop writes non-empty .part and returns positive duration
cz::VideoSpec vspec;
vspec.width = 640;
vspec.height = 360;
vspec.fps = 15;
vspec.bitrate_bps = 2000000;
vspec.audio_enabled = false;
vspec.tmp_path = tmp.path + "/.VID_test.mp4.part";
assert(sim.start_video(vspec, err));
assert(sim.status().recording);
std::this_thread::sleep_for(std::chrono::milliseconds(60));
cz::VideoStopResult vstop = sim.stop_video();
assert(vstop.ok);
assert(vstop.duration_sec > 0.0);
assert(vstop.bytes > 0);
assert(!sim.status().recording);
struct stat st {};
assert(::stat(vspec.tmp_path.c_str(), &st) == 0);
assert(st.st_size > 0);
sim.stop();
assert(!sim.status().ready);
}
void test_subprocess_backend_with_mock_driver() {
TempDir tmp("subproc_mock");
const std::string cam_bin =
std::string(CZ_SOURCE_DIR) + "/cam-helper/bin/czcamera-cam";
const std::string log_path = tmp.path + "/logs/czcamera.log";
EnvVarGuard env_bin("CZCAMERA_CAM_BIN", cam_bin);
EnvVarGuard env_log("CZCAMERA_LOG", log_path);
EnvVarGuard env_backend("CZCAMERA_BACKEND", "subprocess");
// Factory honors CZCAMERA_BACKEND=subprocess + CZCAMERA_CAM_BIN
{
auto factory_backend = cz::create_camera_backend(false);
assert(factory_backend != nullptr);
assert(factory_backend->status().backend_name == "picamera2-subprocess");
}
cz::SubprocessCameraBackend backend("", {"--mock-driver"});
assert(!backend.status().ready);
cz::CameraStreamSpec spec;
spec.mode = "photo";
spec.main_width = 1640;
spec.main_height = 1232;
spec.preview_width = 226;
spec.preview_height = 170;
spec.fps = 30;
spec.zoom = 1.0f;
spec.ev = 0.0f;
spec.camera_transform = "auto";
std::string err;
assert(backend.start(spec, err));
assert(err.empty());
assert(backend.status().ready);
assert(backend.status().backend_name == "picamera2-subprocess");
assert(backend.child_pid() > 0);
// Receive live PreviewFrames over CZFR pipe
cz::PreviewFrame f1;
assert(wait_for_preview_frame(backend, 0, f1));
assert(f1.width == 226 && f1.height == 170);
assert(f1.rgb24.size() == 226u * 170u * 3u);
assert(!f1.is_16_9);
cz::PreviewFrame f2;
assert(wait_for_preview_frame(backend, f1.seq, f2));
assert(f2.seq > f1.seq);
// Live controls
assert(backend.set_controls(2.0f, -0.5f, err));
// Capture still via helper -> valid JPEG decodable by libjpeg
const std::string jpg_tmp = tmp.path + "/.IMG_mock.jpg.tmp";
cz::StillCaptureResult still = backend.capture_still(jpg_tmp, 640, 480);
assert(still.ok);
assert(still.width == 640 && still.height == 480);
assert(still.bytes > 0);
cz::RgbImage img;
assert(cz::decode_jpeg_rgb24(jpg_tmp, img, err));
assert(img.width == 640 && img.height == 480);
// Start/stop video
cz::VideoSpec vspec;
vspec.width = 1280;
vspec.height = 720;
vspec.fps = 30;
vspec.bitrate_bps = 4000000;
vspec.audio_enabled = true;
vspec.tmp_path = tmp.path + "/.VID_mock.mp4.part";
assert(backend.start_video(vspec, err));
assert(backend.status().recording);
std::this_thread::sleep_for(std::chrono::milliseconds(80));
cz::VideoStopResult vstop = backend.stop_video();
assert(vstop.ok);
assert(vstop.duration_sec > 0.0);
assert(vstop.bytes > 0);
assert(vstop.audio_recorded);
assert(!backend.status().recording);
// Reconfigure back to 16:9 preview + explicit transform and wait for 226x128
cz::CameraStreamSpec spec16;
spec16.mode = "video";
spec16.main_width = 1280;
spec16.main_height = 720;
spec16.preview_width = 226;
spec16.preview_height = 128;
spec16.fps = 30;
spec16.zoom = 1.5f;
spec16.ev = 0.5f;
spec16.camera_transform = "180";
assert(backend.reconfigure(spec16, err));
cz::PreviewFrame f16;
uint64_t seen_seq = f2.seq;
bool got_16_9 = false;
const auto reconf_dl =
std::chrono::steady_clock::now() + std::chrono::seconds(3);
while (std::chrono::steady_clock::now() < reconf_dl) {
if (backend.copy_latest_preview(seen_seq, f16)) {
seen_seq = f16.seq;
if (f16.width == 226 && f16.height == 128 && f16.is_16_9) {
got_16_9 = true;
break;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
assert(got_16_9);
assert(f16.rgb24.size() == 226u * 128u * 3u);
// Pause & resume
assert(backend.pause(err));
assert(backend.status().paused);
assert(backend.resume(err));
assert(!backend.status().paused);
cz::PreviewFrame f_resumed;
assert(wait_for_preview_frame(backend, f16.seq, f_resumed));
assert(f_resumed.seq > f16.seq);
const pid_t pid = backend.child_pid();
backend.stop();
assert(!backend.status().ready);
assert(backend.child_pid() == -1);
int st = 0;
assert(::waitpid(pid, &st, WNOHANG) == -1 && errno == ECHILD);
assert(fs::exists(fs::path(log_path).parent_path()));
}
void test_subprocess_backend_crash_recovery_no_deadlock() {
TempDir tmp("subproc_crash");
const std::string cam_bin =
std::string(CZ_SOURCE_DIR) + "/cam-helper/bin/czcamera-cam";
const std::string log_path = tmp.path + "/czcamera.log";
EnvVarGuard env_log("CZCAMERA_LOG", log_path);
// Part A: SIGKILL mid-stream against real czcamera-cam --mock-driver
{
cz::SubprocessCameraBackend backend(cam_bin, {"--mock-driver"});
cz::CameraStreamSpec spec;
spec.preview_width = 226;
spec.preview_height = 170;
std::string err;
assert(backend.start(spec, err));
cz::PreviewFrame f1;
assert(wait_for_preview_frame(backend, 0, f1));
const pid_t crashed_pid = backend.child_pid();
assert(crashed_pid > 0);
assert(::kill(crashed_pid, SIGKILL) == 0);
// Wait briefly for stdout reader thread to observe EOF and reap child
const auto deadline =
std::chrono::steady_clock::now() + std::chrono::seconds(2);
while (backend.status().ready &&
std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
const cz::BackendHealth health = backend.status();
assert(!health.ready);
assert(!health.last_error.empty());
// Subsequent calls return cleanly with ok=false without SIGPIPE or deadlock
const cz::StillCaptureResult still =
backend.capture_still(tmp.path + "/.dead.jpg.tmp", 640, 480);
assert(!still.ok);
assert(!still.error.empty());
assert(!backend.set_controls(2.0f, 0.0f, err));
assert(!err.empty());
// Ensure crashed PID was reaped (no zombie)
int st = 0;
assert(::waitpid(crashed_pid, &st, WNOHANG) == -1 && errno == ECHILD);
// Restarting spawns a fresh worker cleanly
assert(backend.start(spec, err));
assert(backend.status().ready);
const pid_t fresh_pid = backend.child_pid();
assert(fresh_pid > 0 && fresh_pid != crashed_pid);
cz::PreviewFrame f_fresh;
assert(wait_for_preview_frame(backend, 0, f_fresh));
assert(f_fresh.width == 226 && f_fresh.height == 170);
backend.stop();
assert(::waitpid(fresh_pid, &st, WNOHANG) == -1 && errno == ECHILD);
}
// Part B: SIGKILL mid-command while capture_still() is blocked waiting on reply
{
const std::string stall_helper = tmp.path + "/stall_helper.py";
{
std::ofstream out(stall_helper);
assert(out.is_open());
out << "#!/usr/bin/python3\n"
<< "import json, sys, time\n"
<< "sys.stdout.write(json.dumps({'event':'ready','protocol':1,'backend':'mock','has_audio':False}) + '\\n')\n"
<< "sys.stdout.flush()\n"
<< "for line in sys.stdin:\n"
<< " msg = json.loads(line)\n"
<< " if msg.get('cmd') == 'capture_still':\n"
<< " time.sleep(30.0)\n"
<< " else:\n"
<< " sys.stdout.write(json.dumps({'id': msg.get('id'), 'ok': True}) + '\\n')\n"
<< " sys.stdout.flush()\n";
}
assert(::chmod(stall_helper.c_str(), 0755) == 0);
cz::SubprocessCameraBackend backend(stall_helper);
cz::CameraStreamSpec spec;
std::string err;
assert(backend.start(spec, err));
const pid_t stalled_pid = backend.child_pid();
assert(stalled_pid > 0);
// Trigger SIGKILL shortly after capture_still starts waiting
std::thread killer([stalled_pid]() {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
::kill(stalled_pid, SIGKILL);
});
const auto t0 = std::chrono::steady_clock::now();
const cz::StillCaptureResult still =
backend.capture_still(tmp.path + "/.hung.jpg.tmp", 640, 480);
const auto elapsed_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0)
.count();
killer.join();
assert(!still.ok);
assert(!still.error.empty());
assert(elapsed_ms < 2000); // Must wake immediately, well before 5s timeout!
assert(!backend.status().ready);
backend.stop();
}
// Part C: PIXFMT_RGB24 framing + warn("audio_unavailable") event + missing binary
{
const std::string rgb_warn_helper = tmp.path + "/rgb_warn_helper.py";
{
std::ofstream out(rgb_warn_helper);
assert(out.is_open());
out << "#!/usr/bin/python3\n"
<< "import argparse, json, os, struct, sys\n"
<< "p = argparse.ArgumentParser()\n"
<< "p.add_argument('--frame-fd', type=int, required=True)\n"
<< "args = p.parse_args()\n"
<< "sys.stdout.write(json.dumps({'event':'ready','protocol':1,'backend':'mock','has_audio':False}) + '\\n')\n"
<< "sys.stdout.flush()\n"
<< "for line in sys.stdin:\n"
<< " msg = json.loads(line)\n"
<< " cmd = msg.get('cmd')\n"
<< " if cmd == 'configure':\n"
<< " w, h = int(msg['preview_w']), int(msg['preview_h'])\n"
<< " rgb = bytes([12, 34, 56]) * (w * h)\n"
<< " hdr = struct.pack('<4sHHBBHI', b'CZFR', w, h, 2, 0, 0, len(rgb))\n"
<< " os.write(args.frame_fd, hdr + rgb)\n"
<< " sys.stdout.write(json.dumps({'id': msg['id'], 'ok': True}) + '\\n')\n"
<< " elif cmd == 'start_video':\n"
<< " sys.stdout.write(json.dumps({'event':'warn','code':'audio_unavailable','message':'ALSA muted fallback'}) + '\\n')\n"
<< " sys.stdout.write(json.dumps({'id': msg['id'], 'ok': True, 'audio_recorded': False}) + '\\n')\n"
<< " elif cmd == 'shutdown':\n"
<< " sys.stdout.write(json.dumps({'id': msg['id'], 'ok': True}) + '\\n')\n"
<< " sys.stdout.flush()\n"
<< " break\n"
<< " else:\n"
<< " sys.stdout.write(json.dumps({'id': msg['id'], 'ok': True}) + '\\n')\n"
<< " sys.stdout.flush()\n";
}
assert(::chmod(rgb_warn_helper.c_str(), 0755) == 0);
cz::SubprocessCameraBackend backend(rgb_warn_helper);
cz::CameraStreamSpec spec;
spec.preview_width = 226;
spec.preview_height = 170;
std::string err;
assert(backend.start(spec, err));
cz::PreviewFrame rgb_frame;
assert(wait_for_preview_frame(backend, 0, rgb_frame));
assert(rgb_frame.width == 226 && rgb_frame.height == 170);
assert(rgb_frame.rgb24.size() == 226u * 170u * 3u);
assert(rgb_frame.rgb24[0] == 12 && rgb_frame.rgb24[1] == 34 &&
rgb_frame.rgb24[2] == 56);
cz::VideoSpec vspec;
vspec.width = 1280;
vspec.height = 720;
vspec.fps = 30;
vspec.audio_enabled = true;
vspec.tmp_path = tmp.path + "/.VID_warn.mp4.part";
assert(backend.start_video(vspec, err));
const cz::BackendHealth h = backend.status();
assert(h.recording);
assert(h.audio_warning);
assert(h.last_error == "ALSA muted fallback");
backend.stop();
// Missing helper binary fails fast without waiting for 5s ready timeout
cz::SubprocessCameraBackend missing("/nonexistent/czcamera_missing_helper");
const auto t0 = std::chrono::steady_clock::now();
assert(!missing.start(spec, err));
const auto miss_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0)
.count();
assert(!err.empty());
assert(!missing.status().ready);
assert(miss_ms < 2000);
}
}
} // namespace
int main() {
test_czfr_header_and_yuv420_to_rgb24();
test_sim_backend_lifecycle();
test_subprocess_backend_with_mock_driver();
test_subprocess_backend_crash_recovery_no_deadlock();
std::cout << "All test_backend_protocol tests passed!\n";
return 0;
}