feat(app): add CMake scaffold, shadcn Zinc themes, fb blit, config, and sync-safe storage

This commit is contained in:
2026-11-19 13:23:25 -05:00
parent 57c734fd2c
commit b6a4dacbde
9 changed files with 1947 additions and 0 deletions

75
app/CMakeLists.txt Normal file
View File

@@ -0,0 +1,75 @@
cmake_minimum_required(VERSION 3.16)
project(czcamera LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(CZ_BUILD_APP "Build czcamera application binary" OFF)
option(CZ_TARGET_DEVICE "Build for CardputerZero Linux fbdev/evdev target" OFF)
option(CZ_BUILD_TESTS "Build czcamera unit tests" ON)
option(CZ_ENABLE_LVGL "Enable optional LVGL UI hook if available" OFF)
find_package(JPEG REQUIRED)
find_package(Freetype QUIET)
find_package(Threads REQUIRED)
if(CZ_ENABLE_LVGL)
find_package(lvgl QUIET)
endif()
add_library(czcamera_core STATIC
src/theme.cpp
src/config.cpp
src/storage.cpp
)
target_include_directories(czcamera_core
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/src
)
target_compile_options(czcamera_core
PRIVATE
-Wall
-Wextra
-Wpedantic
)
target_link_libraries(czcamera_core
PUBLIC
Threads::Threads
)
if(Freetype_FOUND)
target_compile_definitions(czcamera_core PUBLIC CZ_HAS_FREETYPE=1)
target_link_libraries(czcamera_core PUBLIC Freetype::Freetype)
endif()
if(CZ_ENABLE_LVGL AND lvgl_FOUND)
target_compile_definitions(czcamera_core PUBLIC CP0_HAS_LVGL=1)
target_link_libraries(czcamera_core PUBLIC lvgl::lvgl)
endif()
if(CZ_BUILD_APP)
if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp")
message(FATAL_ERROR "CZ_BUILD_APP=ON requires src/main.cpp")
endif()
add_executable(czcamera src/main.cpp)
target_compile_options(czcamera PRIVATE -Wall -Wextra -Wpedantic)
target_link_libraries(czcamera PRIVATE czcamera_core JPEG::JPEG)
if(CZ_TARGET_DEVICE)
target_compile_definitions(czcamera PRIVATE CZ_TARGET_DEVICE=1)
else()
find_package(SDL2 REQUIRED)
target_link_libraries(czcamera PRIVATE SDL2::SDL2)
endif()
endif()
if(CZ_BUILD_TESTS)
enable_testing()
add_executable(test_config_and_storage tests/test_config_and_storage.cpp)
target_compile_options(test_config_and_storage PRIVATE -Wall -Wextra -Wpedantic)
target_link_libraries(test_config_and_storage PRIVATE czcamera_core)
add_test(NAME test_config_and_storage COMMAND test_config_and_storage)
endif()

546
app/src/config.cpp Normal file
View File

@@ -0,0 +1,546 @@
#include "config.hpp"
#include "storage.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <unistd.h>
namespace cz {
namespace {
bool is_one_of(const std::string& val, std::initializer_list<const char*> opts) {
for (const char* opt : opts) {
if (val == opt) {
return true;
}
}
return false;
}
AppConfig sanitize_config(AppConfig cfg) {
if (cfg.output_dir.empty()) {
cfg.output_dir = "~/Pictures/czcamera";
}
if (!is_one_of(cfg.theme, {"dark", "light"})) {
cfg.theme = "dark";
}
if (!is_one_of(cfg.rail_side, {"right", "left"})) {
cfg.rail_side = "right";
}
if (!is_one_of(cfg.photo_resolution, {"8mp", "2mp"})) {
cfg.photo_resolution = "8mp";
}
if (!is_one_of(cfg.photo_filter,
{"none", "bw", "hicon", "sepia", "cool", "vivid", "invert",
"retro", "gameboy"})) {
cfg.photo_filter = "none";
}
if (cfg.photo_timer_sec != 0 && cfg.photo_timer_sec != 3 &&
cfg.photo_timer_sec != 10) {
cfg.photo_timer_sec = 0;
}
if (!is_one_of(cfg.video_resolution, {"480p", "720p", "1080p"})) {
cfg.video_resolution = "720p";
}
if (!is_one_of(cfg.timelapse_resolution, {"2mp", "1080p", "8mp"})) {
cfg.timelapse_resolution = "2mp";
}
cfg.timelapse_interval_sec = std::clamp(cfg.timelapse_interval_sec, 1, 3600);
if (!is_one_of(cfg.timelapse_output_mode, {"video", "photos"})) {
cfg.timelapse_output_mode = "video";
}
if (cfg.timelapse_fps != 15 && cfg.timelapse_fps != 24 &&
cfg.timelapse_fps != 30) {
cfg.timelapse_fps = 24;
}
if (!is_one_of(cfg.timelapse_stop_mode, {"manual", "shots", "duration"})) {
cfg.timelapse_stop_mode = "manual";
}
cfg.timelapse_stop_value = std::max(0, cfg.timelapse_stop_value);
cfg.timelapse_dim_sec = std::clamp(cfg.timelapse_dim_sec, 0, 3600);
if (!std::isfinite(cfg.ev)) {
cfg.ev = 0.0;
} else {
cfg.ev = std::clamp(cfg.ev, -2.0, 2.0);
}
if (!is_one_of(cfg.camera_transform, {"auto", "0", "180", "hflip", "vflip"})) {
cfg.camera_transform = "auto";
}
return cfg;
}
class JsonParser {
public:
explicit JsonParser(const std::string& src) : src_(src), pos_(0) {}
bool parse_root(std::map<std::string, json_detail::JsonValue>& out) {
out.clear();
skip_ws();
if (!consume('{')) {
return false;
}
skip_ws();
if (peek() == '}') {
++pos_;
skip_ws();
return pos_ == src_.size();
}
while (true) {
skip_ws();
std::string key;
if (!parse_string(key)) {
return false;
}
skip_ws();
if (!consume(':')) {
return false;
}
skip_ws();
json_detail::JsonValue val;
if (!parse_value(val)) {
return false;
}
out[key] = val;
skip_ws();
if (consume(',')) {
continue;
}
if (consume('}')) {
skip_ws();
return pos_ == src_.size();
}
return false;
}
}
private:
const std::string& src_;
size_t pos_;
char peek() const { return pos_ < src_.size() ? src_[pos_] : '\0'; }
void skip_ws() {
while (pos_ < src_.size() &&
(src_[pos_] == ' ' || src_[pos_] == '\t' || src_[pos_] == '\n' ||
src_[pos_] == '\r')) {
++pos_;
}
}
bool consume(char c) {
if (pos_ < src_.size() && src_[pos_] == c) {
++pos_;
return true;
}
return false;
}
bool match_literal(const char* lit, size_t len) {
if (pos_ + len > src_.size()) {
return false;
}
if (src_.compare(pos_, len, lit) == 0) {
pos_ += len;
return true;
}
return false;
}
static void append_utf8(uint32_t cp, std::string& out) {
if (cp <= 0x7Fu) {
out.push_back(static_cast<char>(cp));
} else if (cp <= 0x7FFu) {
out.push_back(static_cast<char>(0xC0u | (cp >> 6)));
out.push_back(static_cast<char>(0x80u | (cp & 0x3Fu)));
} else {
out.push_back(static_cast<char>(0xE0u | (cp >> 12)));
out.push_back(static_cast<char>(0x80u | ((cp >> 6) & 0x3Fu)));
out.push_back(static_cast<char>(0x80u | (cp & 0x3Fu)));
}
}
bool parse_hex4(uint32_t& cp) {
if (pos_ + 4 > src_.size()) {
return false;
}
cp = 0;
for (int i = 0; i < 4; ++i) {
const char c = src_[pos_++];
cp <<= 4;
if (c >= '0' && c <= '9') {
cp |= static_cast<uint32_t>(c - '0');
} else if (c >= 'a' && c <= 'f') {
cp |= static_cast<uint32_t>(10 + (c - 'a'));
} else if (c >= 'A' && c <= 'F') {
cp |= static_cast<uint32_t>(10 + (c - 'A'));
} else {
return false;
}
}
return true;
}
bool parse_string(std::string& out) {
out.clear();
if (!consume('"')) {
return false;
}
while (pos_ < src_.size()) {
const unsigned char uc = static_cast<unsigned char>(src_[pos_++]);
if (uc == '"') {
return true;
}
if (uc < 0x20u) {
return false;
}
if (uc == '\\') {
if (pos_ >= src_.size()) {
return false;
}
const char esc = src_[pos_++];
switch (esc) {
case '"': out.push_back('"'); break;
case '\\': out.push_back('\\'); break;
case '/': out.push_back('/'); break;
case 'b': out.push_back('\b'); break;
case 'f': out.push_back('\f'); break;
case 'n': out.push_back('\n'); break;
case 'r': out.push_back('\r'); break;
case 't': out.push_back('\t'); break;
case 'u': {
uint32_t cp = 0;
if (!parse_hex4(cp)) {
return false;
}
append_utf8(cp, out);
break;
}
default:
return false;
}
} else {
out.push_back(static_cast<char>(uc));
}
}
return false;
}
bool parse_number(double& out) {
const size_t start = pos_;
if (peek() == '-') {
++pos_;
}
if (peek() == '0') {
++pos_;
} else if (std::isdigit(static_cast<unsigned char>(peek()))) {
while (std::isdigit(static_cast<unsigned char>(peek()))) {
++pos_;
}
} else {
return false;
}
if (peek() == '.') {
++pos_;
if (!std::isdigit(static_cast<unsigned char>(peek()))) {
return false;
}
while (std::isdigit(static_cast<unsigned char>(peek()))) {
++pos_;
}
}
if (peek() == 'e' || peek() == 'E') {
++pos_;
if (peek() == '+' || peek() == '-') {
++pos_;
}
if (!std::isdigit(static_cast<unsigned char>(peek()))) {
return false;
}
while (std::isdigit(static_cast<unsigned char>(peek()))) {
++pos_;
}
}
const std::string token = src_.substr(start, pos_ - start);
char* endptr = nullptr;
out = std::strtod(token.c_str(), &endptr);
return endptr == token.c_str() + token.size() && std::isfinite(out);
}
bool skip_nested_array() {
if (!consume('[')) {
return false;
}
skip_ws();
if (consume(']')) {
return true;
}
while (true) {
skip_ws();
json_detail::JsonValue unused;
if (!parse_value(unused)) {
return false;
}
skip_ws();
if (consume(',')) {
continue;
}
return consume(']');
}
}
bool skip_nested_object() {
if (!consume('{')) {
return false;
}
skip_ws();
if (consume('}')) {
return true;
}
while (true) {
skip_ws();
std::string k;
if (!parse_string(k)) {
return false;
}
skip_ws();
if (!consume(':')) {
return false;
}
skip_ws();
json_detail::JsonValue unused;
if (!parse_value(unused)) {
return false;
}
skip_ws();
if (consume(',')) {
continue;
}
return consume('}');
}
}
bool parse_value(json_detail::JsonValue& out) {
const char c = peek();
if (c == '"') {
out.type = json_detail::JsonValue::Type::String;
return parse_string(out.str_val);
}
if (c == 't' && match_literal("true", 4)) {
out.type = json_detail::JsonValue::Type::Bool;
out.bool_val = true;
return true;
}
if (c == 'f' && match_literal("false", 5)) {
out.type = json_detail::JsonValue::Type::Bool;
out.bool_val = false;
return true;
}
if (c == 'n' && match_literal("null", 4)) {
out.type = json_detail::JsonValue::Type::Null;
return true;
}
if (c == '-' || std::isdigit(static_cast<unsigned char>(c))) {
out.type = json_detail::JsonValue::Type::Number;
return parse_number(out.num_val);
}
if (c == '[') {
out.type = json_detail::JsonValue::Type::Other;
return skip_nested_array();
}
if (c == '{') {
out.type = json_detail::JsonValue::Type::Other;
return skip_nested_object();
}
return false;
}
};
} // namespace
namespace json_detail {
bool parse_json_object(const std::string& text,
std::map<std::string, JsonValue>& out) {
JsonParser parser(text);
return parser.parse_root(out);
}
std::string escape_json_string(const std::string& input) {
std::string out;
out.reserve(input.size() + 8);
for (unsigned char c : input) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20u) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned>(c));
out += buf;
} else {
out.push_back(static_cast<char>(c));
}
break;
}
}
return out;
}
} // namespace json_detail
std::string expand_user_path(const std::string& path) {
if (path.empty()) {
return path;
}
if (path == "~" || (path.size() >= 2 && path[0] == '~' && path[1] == '/')) {
const char* home = std::getenv("HOME");
if (home && *home) {
std::string base(home);
while (base.size() > 1 && base.back() == '/') {
base.pop_back();
}
return path.size() == 1 ? base : base + path.substr(1);
}
}
return path;
}
std::string default_config_path() {
const char* env_cfg = std::getenv("CZCAMERA_CONFIG");
if (env_cfg && *env_cfg) {
return expand_user_path(env_cfg);
}
return expand_user_path("~/.config/czcamera/config.json");
}
AppConfig load_config(const std::string& path) {
const std::string resolved =
path.empty() ? default_config_path() : expand_user_path(path);
std::ifstream in(resolved, std::ios::binary);
if (!in.is_open()) {
return AppConfig{};
}
const std::string contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
if (contents.empty()) {
return AppConfig{};
}
std::map<std::string, json_detail::JsonValue> obj;
if (!json_detail::parse_json_object(contents, obj)) {
return AppConfig{};
}
AppConfig cfg;
auto get_str = [&](const char* key, std::string& dst) {
auto it = obj.find(key);
if (it != obj.end() &&
it->second.type == json_detail::JsonValue::Type::String) {
dst = it->second.str_val;
}
};
auto get_int = [&](const char* key, int& dst) {
auto it = obj.find(key);
if (it != obj.end() &&
it->second.type == json_detail::JsonValue::Type::Number) {
dst = static_cast<int>(std::llround(it->second.num_val));
}
};
auto get_bool = [&](const char* key, bool& dst) {
auto it = obj.find(key);
if (it != obj.end() &&
it->second.type == json_detail::JsonValue::Type::Bool) {
dst = it->second.bool_val;
}
};
auto get_double = [&](const char* key, double& dst) {
auto it = obj.find(key);
if (it != obj.end() &&
it->second.type == json_detail::JsonValue::Type::Number) {
dst = it->second.num_val;
}
};
get_str("output_dir", cfg.output_dir);
get_str("theme", cfg.theme);
get_str("rail_side", cfg.rail_side);
get_str("photo_resolution", cfg.photo_resolution);
get_str("photo_filter", cfg.photo_filter);
get_int("photo_timer_sec", cfg.photo_timer_sec);
get_bool("grid_enabled", cfg.grid_enabled);
get_str("video_resolution", cfg.video_resolution);
get_bool("video_audio", cfg.video_audio);
get_str("timelapse_resolution", cfg.timelapse_resolution);
get_int("timelapse_interval_sec", cfg.timelapse_interval_sec);
get_str("timelapse_output_mode", cfg.timelapse_output_mode);
get_int("timelapse_fps", cfg.timelapse_fps);
get_str("timelapse_stop_mode", cfg.timelapse_stop_mode);
get_int("timelapse_stop_value", cfg.timelapse_stop_value);
get_int("timelapse_dim_sec", cfg.timelapse_dim_sec);
get_double("ev", cfg.ev);
get_str("camera_transform", cfg.camera_transform);
return sanitize_config(cfg);
}
bool save_config(const AppConfig& config, const std::string& path) {
const AppConfig cfg = sanitize_config(config);
const std::string resolved =
path.empty() ? default_config_path() : expand_user_path(path);
if (resolved.empty()) {
return false;
}
std::ostringstream oss;
oss << std::fixed << std::setprecision(1);
oss << "{\n"
<< " \"output_dir\": \""
<< json_detail::escape_json_string(cfg.output_dir) << "\",\n"
<< " \"theme\": \"" << json_detail::escape_json_string(cfg.theme)
<< "\",\n"
<< " \"rail_side\": \""
<< json_detail::escape_json_string(cfg.rail_side) << "\",\n"
<< " \"photo_resolution\": \""
<< json_detail::escape_json_string(cfg.photo_resolution) << "\",\n"
<< " \"photo_filter\": \""
<< json_detail::escape_json_string(cfg.photo_filter) << "\",\n"
<< " \"photo_timer_sec\": " << cfg.photo_timer_sec << ",\n"
<< " \"grid_enabled\": " << (cfg.grid_enabled ? "true" : "false")
<< ",\n"
<< " \"video_resolution\": \""
<< json_detail::escape_json_string(cfg.video_resolution) << "\",\n"
<< " \"video_audio\": " << (cfg.video_audio ? "true" : "false") << ",\n"
<< " \"timelapse_resolution\": \""
<< json_detail::escape_json_string(cfg.timelapse_resolution) << "\",\n"
<< " \"timelapse_interval_sec\": " << cfg.timelapse_interval_sec << ",\n"
<< " \"timelapse_output_mode\": \""
<< json_detail::escape_json_string(cfg.timelapse_output_mode) << "\",\n"
<< " \"timelapse_fps\": " << cfg.timelapse_fps << ",\n"
<< " \"timelapse_stop_mode\": \""
<< json_detail::escape_json_string(cfg.timelapse_stop_mode) << "\",\n"
<< " \"timelapse_stop_value\": " << cfg.timelapse_stop_value << ",\n"
<< " \"timelapse_dim_sec\": " << cfg.timelapse_dim_sec << ",\n"
<< " \"ev\": " << cfg.ev << ",\n"
<< " \"camera_transform\": \""
<< json_detail::escape_json_string(cfg.camera_transform) << "\"\n"
<< "}\n";
const std::string tmp_path =
resolved + "." + std::to_string(::getpid()) + ".tmp";
std::string err;
return write_file_atomic(tmp_path, resolved, oss.str(), err);
}
} // namespace cz

50
app/src/config.hpp Normal file
View File

@@ -0,0 +1,50 @@
#pragma once
#include <map>
#include <string>
namespace cz {
struct AppConfig {
std::string output_dir = "~/Pictures/czcamera";
std::string theme = "dark";
std::string rail_side = "right";
std::string photo_resolution = "8mp";
std::string photo_filter = "none";
int photo_timer_sec = 0;
bool grid_enabled = true;
std::string video_resolution = "720p";
bool video_audio = true;
std::string timelapse_resolution = "2mp";
int timelapse_interval_sec = 5;
std::string timelapse_output_mode = "video";
int timelapse_fps = 24;
std::string timelapse_stop_mode = "manual";
int timelapse_stop_value = 0;
int timelapse_dim_sec = 15;
double ev = 0.0;
std::string camera_transform = "auto";
};
std::string default_config_path();
std::string expand_user_path(const std::string& path);
AppConfig load_config(const std::string& path = "");
bool save_config(const AppConfig& config, const std::string& path = "");
namespace json_detail {
struct JsonValue {
enum class Type { Null, Bool, Number, String, Other };
Type type = Type::Null;
bool bool_val = false;
double num_val = 0.0;
std::string str_val;
};
bool parse_json_object(const std::string& text,
std::map<std::string, JsonValue>& out);
std::string escape_json_string(const std::string& input);
} // namespace json_detail
} // namespace cz

143
app/src/fb_blit.hpp Normal file
View File

@@ -0,0 +1,143 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
namespace cz {
struct FbChannel {
uint32_t offset = 0;
uint32_t length = 0;
};
struct FbBlitSpec {
uint32_t xres = 0;
uint32_t yres = 0;
uint32_t xres_virtual = 0;
uint32_t yres_virtual = 0;
uint32_t xoffset = 0;
uint32_t yoffset = 0;
uint32_t bits_per_pixel = 0;
uint32_t line_length = 0;
FbChannel red;
FbChannel green;
FbChannel blue;
FbChannel transp;
};
inline uint32_t pack_fb_channel(uint32_t value_8bit, const FbChannel& ch) {
if (ch.length == 0 || ch.offset >= 32) {
return 0u;
}
const uint32_t v = value_8bit & 0xFFu;
uint32_t scaled = 0u;
if (ch.length >= 8u) {
const uint32_t shift = std::min(ch.length - 8u, 24u);
scaled = v << shift;
} else {
scaled = v >> (8u - ch.length);
}
if (ch.length < 32u) {
scaled &= (1u << ch.length) - 1u;
}
return scaled << ch.offset;
}
inline bool valid_fb_channel(const FbChannel& ch, uint32_t bpp, bool required) {
if (ch.length == 0u) {
return !required;
}
if (ch.offset >= bpp || ch.length > bpp) {
return false;
}
return static_cast<uint64_t>(ch.offset) + ch.length <= bpp;
}
inline bool blit_framebuffer(uint8_t* fb_map,
size_t map_size,
const FbBlitSpec& spec,
const uint32_t* src_rgb888,
int src_w,
int src_h) {
if (!fb_map || !src_rgb888 || src_w <= 0 || src_h <= 0) {
return false;
}
if (spec.xres == 0 || spec.yres == 0) {
return false;
}
if (spec.bits_per_pixel != 16u && spec.bits_per_pixel != 24u &&
spec.bits_per_pixel != 32u) {
return false;
}
if (!valid_fb_channel(spec.red, spec.bits_per_pixel, true) ||
!valid_fb_channel(spec.green, spec.bits_per_pixel, true) ||
!valid_fb_channel(spec.blue, spec.bits_per_pixel, true) ||
!valid_fb_channel(spec.transp, spec.bits_per_pixel, false)) {
return false;
}
const uint64_t eff_xvirt =
spec.xres_virtual ? spec.xres_virtual : spec.xres;
const uint64_t eff_yvirt =
spec.yres_virtual ? spec.yres_virtual : spec.yres;
if (static_cast<uint64_t>(spec.xoffset) + spec.xres > eff_xvirt ||
static_cast<uint64_t>(spec.yoffset) + spec.yres > eff_yvirt) {
return false;
}
const uint64_t copy_w =
std::min<uint64_t>(spec.xres, static_cast<uint64_t>(src_w));
const uint64_t copy_h =
std::min<uint64_t>(spec.yres, static_cast<uint64_t>(src_h));
const uint64_t bytes_pp = spec.bits_per_pixel / 8u;
const uint64_t row_bytes_needed =
(static_cast<uint64_t>(spec.xoffset) + copy_w) * bytes_pp;
if (spec.line_length == 0 || spec.line_length < row_bytes_needed) {
return false;
}
const uint64_t last_row = static_cast<uint64_t>(spec.yoffset) + copy_h - 1u;
if (last_row > 0 &&
spec.line_length > (static_cast<uint64_t>(SIZE_MAX) - row_bytes_needed) / last_row) {
return false;
}
const uint64_t required_bytes =
last_row * static_cast<uint64_t>(spec.line_length) + row_bytes_needed;
if (required_bytes > static_cast<uint64_t>(map_size)) {
return false;
}
for (uint64_t y = 0; y < copy_h; ++y) {
const uint64_t dst_row_off =
(static_cast<uint64_t>(spec.yoffset) + y) * spec.line_length +
static_cast<uint64_t>(spec.xoffset) * bytes_pp;
uint8_t* dst = fb_map + dst_row_off;
const uint32_t* src_row = src_rgb888 + y * static_cast<uint64_t>(src_w);
for (uint64_t x = 0; x < copy_w; ++x) {
const uint32_t rgb = src_row[x];
const uint32_t r = (rgb >> 16) & 0xFFu;
const uint32_t g = (rgb >> 8) & 0xFFu;
const uint32_t b = rgb & 0xFFu;
const uint32_t packed = pack_fb_channel(r, spec.red) |
pack_fb_channel(g, spec.green) |
pack_fb_channel(b, spec.blue) |
pack_fb_channel(0xFFu, spec.transp);
uint8_t* px = dst + x * bytes_pp;
px[0] = static_cast<uint8_t>(packed & 0xFFu);
px[1] = static_cast<uint8_t>((packed >> 8) & 0xFFu);
if (bytes_pp >= 3u) {
px[2] = static_cast<uint8_t>((packed >> 16) & 0xFFu);
}
if (bytes_pp == 4u) {
px[3] = static_cast<uint8_t>((packed >> 24) & 0xFFu);
}
}
}
return true;
}
} // namespace cz

507
app/src/storage.cpp Normal file
View File

@@ -0,0 +1,507 @@
#include "storage.hpp"
#include "config.hpp"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <unistd.h>
namespace cz {
namespace {
std::string parent_dir_of(const std::string& path) {
const size_t slash = path.find_last_of('/');
if (slash == std::string::npos) {
return ".";
}
if (slash == 0) {
return "/";
}
return path.substr(0, slash);
}
std::string base_name_of(const std::string& path) {
const size_t slash = path.find_last_of('/');
if (slash == std::string::npos) {
return path;
}
return path.substr(slash + 1);
}
std::string join_path(const std::string& dir, const std::string& name) {
if (dir.empty()) {
return name;
}
if (dir.back() == '/') {
return dir + name;
}
return dir + "/" + name;
}
bool path_exists_lstat(const std::string& path) {
struct stat st {};
return ::lstat(path.c_str(), &st) == 0;
}
std::string current_timestamp_compact() {
const std::time_t now = std::time(nullptr);
struct tm tm_now {};
::localtime_r(&now, &tm_now);
char buf[32];
std::snprintf(buf, sizeof(buf), "%04d%02d%02d_%02d%02d%02d",
tm_now.tm_year + 1900, tm_now.tm_mon + 1, tm_now.tm_mday,
tm_now.tm_hour, tm_now.tm_min, tm_now.tm_sec);
return std::string(buf);
}
void fsync_parent_best_effort(const std::string& path) {
const std::string dir = parent_dir_of(path);
const int dfd = ::open(dir.c_str(), O_RDONLY);
if (dfd >= 0) {
::fsync(dfd);
::close(dfd);
}
}
std::string resolve_manifest_path(const std::string& path_or_dir) {
const std::string expanded = expand_user_path(path_or_dir);
if (expanded.size() >= 5 &&
expanded.compare(expanded.size() - 5, 5, ".json") == 0) {
return expanded;
}
struct stat st {};
if (::stat(expanded.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
return expanded;
}
return join_path(expanded, "session.json");
}
bool ends_with_ci(const std::string& s, const std::string& suffix) {
if (s.size() < suffix.size()) {
return false;
}
const size_t off = s.size() - suffix.size();
for (size_t i = 0; i < suffix.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(s[off + i])) !=
std::tolower(static_cast<unsigned char>(suffix[i]))) {
return false;
}
}
return true;
}
int count_valid_frames_in_dir(const std::string& dir_path) {
DIR* d = ::opendir(dir_path.c_str());
if (!d) {
return 0;
}
int count = 0;
struct dirent* ent = nullptr;
while ((ent = ::readdir(d)) != nullptr) {
const std::string name(ent->d_name);
if (name.empty() || name[0] == '.') {
continue;
}
if (!ends_with_ci(name, ".jpg") && !ends_with_ci(name, ".jpeg")) {
continue;
}
const std::string full = join_path(dir_path, name);
struct stat st {};
if (::stat(full.c_str(), &st) == 0 && S_ISREG(st.st_mode) &&
st.st_size > 0) {
++count;
}
}
::closedir(d);
return count;
}
StagedPaths next_media_paths(const std::string& output_dir,
const std::string& prefix,
const std::string& final_ext,
const std::string& tmp_ext) {
const std::string dir = expand_user_path(output_dir);
mkdir_p(dir);
const std::string ts = current_timestamp_compact();
for (int idx = 0; idx < 1000; ++idx) {
std::string suffix;
if (idx > 0) {
char buf[16];
std::snprintf(buf, sizeof(buf), "_%02d", idx);
suffix = buf;
}
const std::string stem = prefix + "_" + ts + suffix;
const std::string tmp_p = join_path(dir, "." + stem + tmp_ext);
const std::string fin_p = join_path(dir, stem + final_ext);
if (!path_exists_lstat(tmp_p) && !path_exists_lstat(fin_p)) {
return StagedPaths{tmp_p, fin_p};
}
}
const std::string fallback_stem =
prefix + "_" + ts + "_" + std::to_string(::getpid());
return StagedPaths{join_path(dir, "." + fallback_stem + tmp_ext),
join_path(dir, fallback_stem + final_ext)};
}
} // namespace
bool mkdir_p(const std::string& path) {
const std::string expanded = expand_user_path(path);
if (expanded.empty()) {
return false;
}
std::string current;
size_t i = 0;
if (expanded[0] == '/') {
current = "/";
i = 1;
}
while (i <= expanded.size()) {
const size_t next = expanded.find('/', i);
const std::string part = (next == std::string::npos)
? expanded.substr(i)
: expanded.substr(i, next - i);
if (!part.empty()) {
current = join_path(current, part);
struct stat st {};
if (::stat(current.c_str(), &st) == 0) {
if (!S_ISDIR(st.st_mode)) {
return false;
}
} else if (::mkdir(current.c_str(), 0755) != 0 && errno != EEXIST) {
return false;
}
}
if (next == std::string::npos) {
break;
}
i = next + 1;
}
struct stat st {};
return ::stat(expanded.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
bool write_file_atomic(const std::string& tmp_path,
const std::string& final_path,
const std::string& content,
std::string& out_err) {
const std::string parent = parent_dir_of(final_path);
if (!mkdir_p(parent)) {
out_err = "Failed to create directory: " + parent;
return false;
}
const int fd = ::open(tmp_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
out_err = std::string("Failed to open temp file: ") + std::strerror(errno);
return false;
}
size_t written = 0;
while (written < content.size()) {
const ssize_t n =
::write(fd, content.data() + written, content.size() - written);
if (n < 0) {
if (errno == EINTR) {
continue;
}
out_err = std::string("Failed writing temp file: ") + std::strerror(errno);
::close(fd);
::unlink(tmp_path.c_str());
return false;
}
written += static_cast<size_t>(n);
}
if (::fsync(fd) != 0 && errno != EINVAL && errno != ENOTSUP) {
out_err = std::string("fsync failed: ") + std::strerror(errno);
::close(fd);
::unlink(tmp_path.c_str());
return false;
}
if (::close(fd) != 0) {
out_err = std::string("close failed: ") + std::strerror(errno);
::unlink(tmp_path.c_str());
return false;
}
if (::rename(tmp_path.c_str(), final_path.c_str()) != 0) {
out_err = std::string("rename failed: ") + std::strerror(errno);
::unlink(tmp_path.c_str());
return false;
}
fsync_parent_best_effort(final_path);
out_err.clear();
return true;
}
StagedPaths next_photo_paths(const std::string& output_dir) {
return next_media_paths(output_dir, "IMG", ".jpg", ".jpg.tmp");
}
StagedPaths next_video_paths(const std::string& output_dir) {
return next_media_paths(output_dir, "VID", ".mp4", ".mp4.part");
}
TimelapseSessionPaths create_timelapse_session(const std::string& output_dir,
bool create_work_dir) {
const std::string dir = expand_user_path(output_dir);
mkdir_p(dir);
const std::string ts = current_timestamp_compact();
std::string session_id = ts;
for (int idx = 0; idx < 1000; ++idx) {
std::string candidate = ts;
if (idx > 0) {
char buf[16];
std::snprintf(buf, sizeof(buf), "_%02d", idx);
candidate += buf;
}
const std::string work = join_path(dir, ".tl_work_" + candidate);
const std::string photos = join_path(dir, "TL_" + candidate);
const std::string mp4_tmp = join_path(dir, ".TL_" + candidate + ".mp4.part");
const std::string mp4_fin = join_path(dir, "TL_" + candidate + ".mp4");
if (!path_exists_lstat(work) && !path_exists_lstat(photos) &&
!path_exists_lstat(mp4_tmp) && !path_exists_lstat(mp4_fin)) {
session_id = candidate;
break;
}
}
TimelapseSessionPaths paths;
paths.session_id = session_id;
paths.work_dir = join_path(dir, ".tl_work_" + session_id);
paths.photos_dir = join_path(dir, "TL_" + session_id);
paths.manifest_path = join_path(paths.work_dir, "session.json");
paths.mp4_tmp_path = join_path(dir, ".TL_" + session_id + ".mp4.part");
paths.mp4_final_path = join_path(dir, "TL_" + session_id + ".mp4");
if (create_work_dir) {
mkdir_p(paths.work_dir);
}
return paths;
}
StagedPaths next_timelapse_frame_paths(const std::string& dir, int frame_index) {
const std::string expanded = expand_user_path(dir);
char name_buf[32];
std::snprintf(name_buf, sizeof(name_buf), "frame_%04d.jpg",
std::max(1, frame_index));
const std::string frame_name(name_buf);
return StagedPaths{join_path(expanded, "." + frame_name + ".tmp"),
join_path(expanded, frame_name)};
}
bool commit_staged_file(const std::string& tmp_path,
const std::string& final_path,
std::string& out_err) {
struct stat st {};
if (::stat(tmp_path.c_str(), &st) != 0) {
out_err = std::string("Staged file missing: ") + std::strerror(errno);
return false;
}
if (!S_ISREG(st.st_mode)) {
out_err = "Staged path is not a regular file";
return false;
}
if (st.st_size <= 0) {
out_err = "Staged file is empty (0 bytes)";
return false;
}
const int fd = ::open(tmp_path.c_str(), O_RDONLY);
if (fd >= 0) {
::fsync(fd);
::close(fd);
}
if (::rename(tmp_path.c_str(), final_path.c_str()) != 0) {
out_err = std::string("Atomic rename failed: ") + std::strerror(errno);
return false;
}
fsync_parent_best_effort(final_path);
out_err.clear();
return true;
}
bool has_sufficient_storage(const std::string& dir_path,
uint64_t min_bytes,
uint64_t* out_free_bytes) {
std::string probe = expand_user_path(dir_path);
if (probe.empty()) {
probe = ".";
}
struct statvfs vfs {};
while (::statvfs(probe.c_str(), &vfs) != 0) {
if (errno != ENOENT || probe == "/" || probe == ".") {
if (out_free_bytes) {
*out_free_bytes = 0;
}
return false;
}
const std::string next = parent_dir_of(probe);
if (next == probe) {
if (out_free_bytes) {
*out_free_bytes = 0;
}
return false;
}
probe = next;
}
const uint64_t block_size =
vfs.f_frsize > 0 ? static_cast<uint64_t>(vfs.f_frsize)
: static_cast<uint64_t>(vfs.f_bsize);
const uint64_t avail = static_cast<uint64_t>(vfs.f_bavail);
const uint64_t free_bytes =
(block_size > 0 && avail > UINT64_MAX / block_size)
? UINT64_MAX
: avail * block_size;
if (out_free_bytes) {
*out_free_bytes = free_bytes;
}
return free_bytes >= min_bytes;
}
bool write_timelapse_manifest(const std::string& path_or_dir,
const TimelapseManifest& manifest) {
const std::string manifest_path = resolve_manifest_path(path_or_dir);
const std::string dir = parent_dir_of(manifest_path);
const std::string base = base_name_of(manifest_path);
const std::string tmp_path =
join_path(dir, "." + base + "." + std::to_string(::getpid()) + ".tmp");
std::ostringstream oss;
oss << "{\n"
<< " \"session_id\": \""
<< json_detail::escape_json_string(manifest.session_id) << "\",\n"
<< " \"created_at\": \""
<< json_detail::escape_json_string(manifest.created_at) << "\",\n"
<< " \"resolution\": \""
<< json_detail::escape_json_string(manifest.resolution) << "\",\n"
<< " \"interval_sec\": " << manifest.interval_sec << ",\n"
<< " \"fps\": " << manifest.fps << ",\n"
<< " \"frame_count\": " << manifest.frame_count << ",\n"
<< " \"status\": \"" << json_detail::escape_json_string(manifest.status)
<< "\"\n"
<< "}\n";
std::string err;
return write_file_atomic(tmp_path, manifest_path, oss.str(), err);
}
bool read_timelapse_manifest(const std::string& path_or_dir,
TimelapseManifest& out_manifest) {
const std::string manifest_path = resolve_manifest_path(path_or_dir);
std::ifstream in(manifest_path, std::ios::binary);
if (!in.is_open()) {
return false;
}
const std::string contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
std::map<std::string, json_detail::JsonValue> obj;
if (!json_detail::parse_json_object(contents, obj)) {
return false;
}
TimelapseManifest m;
m.work_dir = parent_dir_of(manifest_path);
const std::string dir_name = base_name_of(m.work_dir);
if (dir_name.rfind(".tl_work_", 0) == 0) {
m.session_id = dir_name.substr(9);
}
auto get_str = [&](const char* key, std::string& dst) {
auto it = obj.find(key);
if (it != obj.end() &&
it->second.type == json_detail::JsonValue::Type::String) {
dst = it->second.str_val;
}
};
auto get_int = [&](const char* key, int& dst) {
auto it = obj.find(key);
if (it != obj.end() &&
it->second.type == json_detail::JsonValue::Type::Number) {
dst = static_cast<int>(std::llround(it->second.num_val));
}
};
get_str("session_id", m.session_id);
get_str("created_at", m.created_at);
get_str("resolution", m.resolution);
get_int("interval_sec", m.interval_sec);
get_int("fps", m.fps);
get_int("frame_count", m.frame_count);
get_str("status", m.status);
out_manifest = m;
return true;
}
std::vector<TimelapseManifest> scan_orphaned_timelapses(
const std::string& output_dir) {
std::vector<TimelapseManifest> results;
const std::string dir = expand_user_path(output_dir);
DIR* d = ::opendir(dir.c_str());
if (!d) {
return results;
}
struct dirent* ent = nullptr;
while ((ent = ::readdir(d)) != nullptr) {
const std::string name(ent->d_name);
if (name.rfind(".tl_work_", 0) != 0) {
continue;
}
const std::string work_dir = join_path(dir, name);
struct stat st {};
if (::stat(work_dir.c_str(), &st) != 0 || !S_ISDIR(st.st_mode)) {
continue;
}
const int valid_frames = count_valid_frames_in_dir(work_dir);
if (valid_frames <= 0) {
continue;
}
TimelapseManifest m;
if (!read_timelapse_manifest(work_dir, m)) {
m.session_id = name.substr(9);
m.work_dir = work_dir;
m.status = "orphaned";
}
if (m.session_id.empty()) {
m.session_id = name.substr(9);
}
m.work_dir = work_dir;
m.frame_count = valid_frames;
results.push_back(m);
}
::closedir(d);
std::sort(results.begin(), results.end(),
[](const TimelapseManifest& a, const TimelapseManifest& b) {
return a.session_id < b.session_id;
});
return results;
}
} // namespace cz

62
app/src/storage.hpp Normal file
View File

@@ -0,0 +1,62 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace cz {
struct StagedPaths {
std::string tmp_path;
std::string final_path;
};
struct TimelapseSessionPaths {
std::string session_id;
std::string work_dir;
std::string photos_dir;
std::string manifest_path;
std::string mp4_tmp_path;
std::string mp4_final_path;
};
struct TimelapseManifest {
std::string session_id;
std::string work_dir;
std::string created_at;
std::string resolution = "2mp";
int interval_sec = 5;
int fps = 24;
int frame_count = 0;
std::string status = "recording";
};
bool mkdir_p(const std::string& path);
bool write_file_atomic(const std::string& tmp_path,
const std::string& final_path,
const std::string& content,
std::string& out_err);
StagedPaths next_photo_paths(const std::string& output_dir);
StagedPaths next_video_paths(const std::string& output_dir);
TimelapseSessionPaths create_timelapse_session(const std::string& output_dir,
bool create_work_dir = true);
StagedPaths next_timelapse_frame_paths(const std::string& dir, int frame_index);
bool commit_staged_file(const std::string& tmp_path,
const std::string& final_path,
std::string& out_err);
bool has_sufficient_storage(const std::string& dir_path,
uint64_t min_bytes = 104857600ULL,
uint64_t* out_free_bytes = nullptr);
bool write_timelapse_manifest(const std::string& path_or_dir,
const TimelapseManifest& manifest);
bool read_timelapse_manifest(const std::string& path_or_dir,
TimelapseManifest& out_manifest);
std::vector<TimelapseManifest> scan_orphaned_timelapses(
const std::string& output_dir);
} // namespace cz

70
app/src/theme.cpp Normal file
View File

@@ -0,0 +1,70 @@
#include "theme.hpp"
#include <algorithm>
#include <cctype>
namespace cz {
ShadcnPalette get_palette(ThemeMode mode) {
if (mode == ThemeMode::Light) {
ShadcnPalette p;
p.mode = ThemeMode::Light;
p.background = 0xfafafa;
p.card = 0xffffff;
p.muted = 0xf4f4f5;
p.border = 0xe4e4e7;
p.ring = 0x71717a;
p.foreground = 0x09090b;
p.muted_foreground = 0x71717a;
p.active_tab = 0xffffff;
p.active_tab_foreground = 0x09090b;
p.status_online = 0x16a34a;
p.status_online_bg = 0xdcfce7;
p.status_sleeping = 0xd97706;
p.status_sleeping_bg = 0xfef3c7;
p.status_error = 0xdc2626;
p.status_error_bg = 0xfee2e2;
p.viewfinder_surround = 0x050507;
return p;
}
ShadcnPalette p;
p.mode = ThemeMode::Dark;
p.background = 0x09090b;
p.card = 0x09090b;
p.muted = 0x18181b;
p.border = 0x27272a;
p.ring = 0xd4d4d8;
p.foreground = 0xfafafa;
p.muted_foreground = 0xa1a1aa;
p.active_tab = 0x27272a;
p.active_tab_foreground = 0xfafafa;
p.status_online = 0x4ade80;
p.status_online_bg = 0x11261a;
p.status_sleeping = 0xfbbf24;
p.status_sleeping_bg = 0x271d0b;
p.status_error = 0xf87171;
p.status_error_bg = 0x2b1214;
p.viewfinder_surround = 0x050507;
return p;
}
ThemeMode toggle_theme(ThemeMode mode) {
return mode == ThemeMode::Dark ? ThemeMode::Light : ThemeMode::Dark;
}
std::string theme_to_string(ThemeMode mode) {
return mode == ThemeMode::Light ? "light" : "dark";
}
ThemeMode theme_from_string(const std::string& value) {
std::string lower = value;
std::transform(lower.begin(), lower.end(), lower.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (lower == "light") {
return ThemeMode::Light;
}
return ThemeMode::Dark;
}
} // namespace cz

38
app/src/theme.hpp Normal file
View File

@@ -0,0 +1,38 @@
#pragma once
#include <cstdint>
#include <string>
namespace cz {
enum class ThemeMode {
Dark,
Light,
};
struct ShadcnPalette {
ThemeMode mode = ThemeMode::Dark;
uint32_t background = 0x09090b;
uint32_t card = 0x09090b;
uint32_t muted = 0x18181b;
uint32_t border = 0x27272a;
uint32_t ring = 0xd4d4d8;
uint32_t foreground = 0xfafafa;
uint32_t muted_foreground = 0xa1a1aa;
uint32_t active_tab = 0x27272a;
uint32_t active_tab_foreground = 0xfafafa;
uint32_t status_online = 0x4ade80;
uint32_t status_online_bg = 0x11261a;
uint32_t status_sleeping = 0xfbbf24;
uint32_t status_sleeping_bg = 0x271d0b;
uint32_t status_error = 0xf87171;
uint32_t status_error_bg = 0x2b1214;
uint32_t viewfinder_surround = 0x050507;
};
ShadcnPalette get_palette(ThemeMode mode);
ThemeMode toggle_theme(ThemeMode mode);
std::string theme_to_string(ThemeMode mode);
ThemeMode theme_from_string(const std::string& value);
} // namespace cz

View File

@@ -0,0 +1,456 @@
#include "config.hpp"
#include "fb_blit.hpp"
#include "storage.hpp"
#include "theme.hpp"
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#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);
}
};
void write_bytes(const std::string& path, const std::string& data) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
assert(out.is_open());
out.write(data.data(), static_cast<std::streamsize>(data.size()));
out.close();
assert(out.good());
}
std::string read_text(const std::string& path) {
std::ifstream in(path, std::ios::binary);
assert(in.is_open());
return std::string((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
}
void test_theme_tokens_and_toggle() {
const cz::ShadcnPalette dark = cz::get_palette(cz::ThemeMode::Dark);
assert(dark.background == 0x09090b);
assert(dark.card == 0x09090b);
assert(dark.muted == 0x18181b);
assert(dark.border == 0x27272a);
assert(dark.ring == 0xd4d4d8);
assert(dark.foreground == 0xfafafa);
assert(dark.muted_foreground == 0xa1a1aa);
assert(dark.status_online == 0x4ade80);
assert(dark.status_sleeping == 0xfbbf24);
assert(dark.status_error == 0xf87171);
assert(dark.viewfinder_surround == 0x050507);
const cz::ShadcnPalette light = cz::get_palette(cz::ThemeMode::Light);
assert(light.background == 0xfafafa);
assert(light.card == 0xffffff);
assert(light.muted == 0xf4f4f5);
assert(light.border == 0xe4e4e7);
assert(light.ring == 0x71717a);
assert(light.foreground == 0x09090b);
assert(light.muted_foreground == 0x71717a);
assert(light.status_online == 0x16a34a);
assert(light.status_sleeping == 0xd97706);
assert(light.status_error == 0xdc2626);
assert(light.viewfinder_surround == 0x050507);
assert(cz::toggle_theme(cz::ThemeMode::Dark) == cz::ThemeMode::Light);
assert(cz::toggle_theme(cz::ThemeMode::Light) == cz::ThemeMode::Dark);
assert(cz::theme_to_string(cz::ThemeMode::Dark) == "dark");
assert(cz::theme_to_string(cz::ThemeMode::Light) == "light");
assert(cz::theme_from_string("light") == cz::ThemeMode::Light);
assert(cz::theme_from_string("dark") == cz::ThemeMode::Dark);
assert(cz::theme_from_string("invalid") == cz::ThemeMode::Dark);
}
void test_fb_blit_rgb565_argb32_and_bounds() {
// Channel packing checks
const cz::FbChannel r5{11, 5};
const cz::FbChannel g6{5, 6};
const cz::FbChannel b5{0, 5};
assert(cz::pack_fb_channel(0xFF, r5) == 0xF800u);
assert(cz::pack_fb_channel(0xFF, g6) == 0x07E0u);
assert(cz::pack_fb_channel(0xFF, b5) == 0x001Fu);
assert(cz::pack_fb_channel(0x00, r5) == 0x0000u);
assert(cz::pack_fb_channel(0xFF, cz::FbChannel{0, 0}) == 0u);
assert(cz::pack_fb_channel(0xFF, cz::FbChannel{32, 8}) == 0u);
// RGB565 blit with xoffset, yoffset, and padded line_length
{
cz::FbBlitSpec spec{};
spec.xres = 2;
spec.yres = 2;
spec.xres_virtual = 4;
spec.yres_virtual = 4;
spec.xoffset = 1;
spec.yoffset = 1;
spec.bits_per_pixel = 16;
spec.line_length = 12; // padded stride > 4*2
spec.red = {11, 5};
spec.green = {5, 6};
spec.blue = {0, 5};
std::vector<uint8_t> fb(spec.yres_virtual * spec.line_length, 0x00);
const uint32_t src[4] = {
0xFF0000, 0x00FF00,
0x0000FF, 0xFFFFFF,
};
assert(cz::blit_framebuffer(fb.data(), fb.size(), spec, src, 2, 2));
auto read16 = [&](uint32_t row, uint32_t col) -> uint16_t {
const size_t off = static_cast<size_t>(row) * spec.line_length +
static_cast<size_t>(col) * 2u;
return static_cast<uint16_t>(fb[off]) |
(static_cast<uint16_t>(fb[off + 1]) << 8);
};
assert(read16(1, 1) == 0xF800u);
assert(read16(1, 2) == 0x07E0u);
assert(read16(2, 1) == 0x001Fu);
assert(read16(2, 2) == 0xFFFFu);
assert(read16(0, 0) == 0x0000u);
}
// XRGB8888 blit check
{
cz::FbBlitSpec spec{};
spec.xres = 2;
spec.yres = 1;
spec.xres_virtual = 2;
spec.yres_virtual = 1;
spec.bits_per_pixel = 32;
spec.line_length = 8;
spec.red = {16, 8};
spec.green = {8, 8};
spec.blue = {0, 8};
spec.transp = {24, 8};
std::vector<uint8_t> fb(8, 0);
const uint32_t src[2] = {0x123456, 0xABCDEF};
assert(cz::blit_framebuffer(fb.data(), fb.size(), spec, src, 2, 1));
const uint32_t p0 = static_cast<uint32_t>(fb[0]) |
(static_cast<uint32_t>(fb[1]) << 8) |
(static_cast<uint32_t>(fb[2]) << 16) |
(static_cast<uint32_t>(fb[3]) << 24);
const uint32_t p1 = static_cast<uint32_t>(fb[4]) |
(static_cast<uint32_t>(fb[5]) << 8) |
(static_cast<uint32_t>(fb[6]) << 16) |
(static_cast<uint32_t>(fb[7]) << 24);
assert(p0 == 0xFF123456u);
assert(p1 == 0xFFABCDEFu);
}
// 24bpp RGB24 blit check
{
cz::FbBlitSpec spec{};
spec.xres = 2;
spec.yres = 1;
spec.xres_virtual = 2;
spec.yres_virtual = 1;
spec.bits_per_pixel = 24;
spec.line_length = 6;
spec.red = {16, 8};
spec.green = {8, 8};
spec.blue = {0, 8};
std::vector<uint8_t> fb(6, 0);
const uint32_t src[2] = {0x112233, 0xAABBCC};
assert(cz::blit_framebuffer(fb.data(), fb.size(), spec, src, 2, 1));
assert(fb[0] == 0x33 && fb[1] == 0x22 && fb[2] == 0x11);
assert(fb[3] == 0xCC && fb[4] == 0xBB && fb[5] == 0xAA);
}
// Bounds / error rejections
{
cz::FbBlitSpec spec{};
spec.xres = 4;
spec.yres = 4;
spec.xres_virtual = 4;
spec.yres_virtual = 4;
spec.bits_per_pixel = 16;
spec.line_length = 8;
spec.red = {11, 5};
spec.green = {5, 6};
spec.blue = {0, 5};
std::vector<uint8_t> fb(32, 0);
std::vector<uint32_t> src(16, 0x112233);
// Undersized map_size
assert(!cz::blit_framebuffer(fb.data(), 16, spec, src.data(), 4, 4));
// xoffset exceeding virtual width
cz::FbBlitSpec bad_xoff = spec;
bad_xoff.xoffset = 1;
assert(!cz::blit_framebuffer(fb.data(), fb.size(), bad_xoff, src.data(), 4, 4));
// yoffset exceeding virtual height
cz::FbBlitSpec bad_yoff = spec;
bad_yoff.yoffset = 1;
assert(!cz::blit_framebuffer(fb.data(), fb.size(), bad_yoff, src.data(), 4, 4));
// Bitfield offset exceeding bits_per_pixel
cz::FbBlitSpec bad_bf = spec;
bad_bf.red = {16, 8};
assert(!cz::blit_framebuffer(fb.data(), fb.size(), bad_bf, src.data(), 4, 4));
// Null pointers / unsupported bpp
assert(!cz::blit_framebuffer(nullptr, fb.size(), spec, src.data(), 4, 4));
assert(!cz::blit_framebuffer(fb.data(), fb.size(), spec, nullptr, 4, 4));
cz::FbBlitSpec bad_bpp = spec;
bad_bpp.bits_per_pixel = 8;
assert(!cz::blit_framebuffer(fb.data(), fb.size(), bad_bpp, src.data(), 4, 4));
}
}
void test_config_defaults_roundtrip_and_corrupt_fallback() {
TempDir tmp("config");
const std::string cfg_path = tmp.path + "/nested/config.json";
// Missing config returns all 18 defaults
const cz::AppConfig def = cz::load_config(cfg_path);
assert(def.output_dir == "~/Pictures/czcamera");
assert(def.theme == "dark");
assert(def.rail_side == "right");
assert(def.photo_resolution == "8mp");
assert(def.photo_filter == "none");
assert(def.photo_timer_sec == 0);
assert(def.grid_enabled == true);
assert(def.video_resolution == "720p");
assert(def.video_audio == true);
assert(def.timelapse_resolution == "2mp");
assert(def.timelapse_interval_sec == 5);
assert(def.timelapse_output_mode == "video");
assert(def.timelapse_fps == 24);
assert(def.timelapse_stop_mode == "manual");
assert(def.timelapse_stop_value == 0);
assert(def.timelapse_dim_sec == 15);
assert(def.ev == 0.0);
assert(def.camera_transform == "auto");
// CZCAMERA_CONFIG override
const std::string env_cfg = tmp.path + "/env_config.json";
::setenv("CZCAMERA_CONFIG", env_cfg.c_str(), 1);
assert(cz::default_config_path() == env_cfg);
// expand_user_path check
const char* home = std::getenv("HOME");
if (home && *home) {
assert(cz::expand_user_path("~/Pictures/czcamera") ==
std::string(home) + "/Pictures/czcamera");
assert(cz::expand_user_path("~") == std::string(home));
}
assert(cz::expand_user_path("/tmp/abc") == "/tmp/abc");
// Save/load round-trip of all 18 fields with non-default values
cz::AppConfig custom;
custom.output_dir = "/tmp/my_cam_dir";
custom.theme = "light";
custom.rail_side = "left";
custom.photo_resolution = "2mp";
custom.photo_filter = "gameboy";
custom.photo_timer_sec = 10;
custom.grid_enabled = false;
custom.video_resolution = "1080p";
custom.video_audio = false;
custom.timelapse_resolution = "8mp";
custom.timelapse_interval_sec = 30;
custom.timelapse_output_mode = "photos";
custom.timelapse_fps = 30;
custom.timelapse_stop_mode = "shots";
custom.timelapse_stop_value = 120;
custom.timelapse_dim_sec = 60;
custom.ev = -1.5;
custom.camera_transform = "180";
assert(cz::save_config(custom));
const cz::AppConfig loaded = cz::load_config();
assert(loaded.output_dir == custom.output_dir);
assert(loaded.theme == custom.theme);
assert(loaded.rail_side == custom.rail_side);
assert(loaded.photo_resolution == custom.photo_resolution);
assert(loaded.photo_filter == custom.photo_filter);
assert(loaded.photo_timer_sec == custom.photo_timer_sec);
assert(loaded.grid_enabled == custom.grid_enabled);
assert(loaded.video_resolution == custom.video_resolution);
assert(loaded.video_audio == custom.video_audio);
assert(loaded.timelapse_resolution == custom.timelapse_resolution);
assert(loaded.timelapse_interval_sec == custom.timelapse_interval_sec);
assert(loaded.timelapse_output_mode == custom.timelapse_output_mode);
assert(loaded.timelapse_fps == custom.timelapse_fps);
assert(loaded.timelapse_stop_mode == custom.timelapse_stop_mode);
assert(loaded.timelapse_stop_value == custom.timelapse_stop_value);
assert(loaded.timelapse_dim_sec == custom.timelapse_dim_sec);
assert(loaded.ev == custom.ev);
assert(loaded.camera_transform == custom.camera_transform);
// Corrupt JSON falls back gracefully to defaults without throwing
write_bytes(env_cfg, "{ \"theme\": \"light\", broken_json ");
const cz::AppConfig recovered = cz::load_config();
assert(recovered.theme == "dark");
assert(recovered.output_dir == "~/Pictures/czcamera");
assert(recovered.timelapse_dim_sec == 15);
assert(recovered.camera_transform == "auto");
::unsetenv("CZCAMERA_CONFIG");
}
void test_sync_safe_staging_collision_storage_floor_and_manifest() {
TempDir tmp("storage");
const std::string out_dir = tmp.path + "/out";
assert(cz::mkdir_p(out_dir));
// Photo staging paths & same-second collision
const cz::StagedPaths p1 = cz::next_photo_paths(out_dir);
const std::string p1_tmp_name = fs::path(p1.tmp_path).filename().string();
const std::string p1_fin_name = fs::path(p1.final_path).filename().string();
assert(fs::path(p1.tmp_path).parent_path() == out_dir);
assert(fs::path(p1.final_path).parent_path() == out_dir);
assert(p1_tmp_name.rfind(".IMG_", 0) == 0);
assert(p1_tmp_name.find(".jpg.tmp") != std::string::npos);
assert(p1_fin_name.rfind("IMG_", 0) == 0);
assert(p1_fin_name.find(".jpg") != std::string::npos);
// Create p1.final_path so next_photo_paths in the same second collides
write_bytes(p1.final_path, "jpegdata");
cz::StagedPaths p2 = cz::next_photo_paths(out_dir);
if (fs::path(p2.final_path).filename().string().substr(0, 19) !=
p1_fin_name.substr(0, 19)) {
// Second rolled over between p1 and p2; collide on p2's second instead.
write_bytes(p2.final_path, "jpegdata");
p2 = cz::next_photo_paths(out_dir);
}
assert(p2.final_path.find("_01.jpg") != std::string::npos);
assert(p2.tmp_path.find("_01.jpg.tmp") != std::string::npos);
assert(p2.final_path != p1.final_path);
// Video staging paths & collision
const cz::StagedPaths v1 = cz::next_video_paths(out_dir);
const std::string v1_tmp_name = fs::path(v1.tmp_path).filename().string();
const std::string v1_fin_name = fs::path(v1.final_path).filename().string();
assert(v1_tmp_name.rfind(".VID_", 0) == 0);
assert(v1_tmp_name.find(".mp4.part") != std::string::npos);
assert(v1_fin_name.rfind("VID_", 0) == 0);
assert(v1_fin_name.find(".mp4") != std::string::npos);
write_bytes(v1.final_path, "mp4data");
cz::StagedPaths v2 = cz::next_video_paths(out_dir);
if (fs::path(v2.final_path).filename().string().substr(0, 19) !=
v1_fin_name.substr(0, 19)) {
write_bytes(v2.final_path, "mp4data");
v2 = cz::next_video_paths(out_dir);
}
assert(v2.final_path.find("_01.mp4") != std::string::npos);
assert(v2.tmp_path.find("_01.mp4.part") != std::string::npos);
assert(v2.final_path != v1.final_path);
// commit_staged_file rejects missing and 0-byte tmp files without leaking
std::string err;
const std::string missing_tmp = out_dir + "/.missing.jpg.tmp";
const std::string missing_final = out_dir + "/missing.jpg";
assert(!cz::commit_staged_file(missing_tmp, missing_final, err));
assert(!err.empty());
assert(!fs::exists(missing_final));
const std::string empty_tmp = out_dir + "/.empty.jpg.tmp";
const std::string empty_final = out_dir + "/empty.jpg";
write_bytes(empty_tmp, "");
assert(!cz::commit_staged_file(empty_tmp, empty_final, err));
assert(!err.empty());
assert(!fs::exists(empty_final));
// Valid non-empty tmp commits cleanly
const std::string good_tmp = out_dir + "/.good.jpg.tmp";
const std::string good_final = out_dir + "/good.jpg";
write_bytes(good_tmp, "valid_jpeg_bytes");
assert(cz::commit_staged_file(good_tmp, good_final, err));
assert(!fs::exists(good_tmp));
assert(fs::exists(good_final));
assert(read_text(good_final) == "valid_jpeg_bytes");
// Storage floor check (104857600ULL default)
uint64_t free_bytes = 0;
const bool ok_default = cz::has_sufficient_storage(out_dir, 104857600ULL, &free_bytes);
assert(free_bytes > 0);
assert(ok_default == (free_bytes >= 104857600ULL));
// Impossibly high threshold must return false
assert(!cz::has_sufficient_storage(out_dir, UINT64_MAX, &free_bytes));
// Timelapse session, manifest I/O, and orphan scanning
const cz::TimelapseSessionPaths sess = cz::create_timelapse_session(out_dir);
assert(fs::is_directory(sess.work_dir));
assert(fs::path(sess.work_dir).filename().string().rfind(".tl_work_", 0) == 0);
cz::TimelapseManifest m;
m.session_id = sess.session_id;
m.work_dir = sess.work_dir;
m.created_at = "2026-11-19T12:30:00Z";
m.resolution = "2mp";
m.interval_sec = 5;
m.fps = 24;
m.frame_count = 2;
m.status = "recording";
assert(cz::write_timelapse_manifest(sess.manifest_path, m));
cz::TimelapseManifest m_read;
assert(cz::read_timelapse_manifest(sess.manifest_path, m_read));
assert(m_read.session_id == m.session_id);
assert(m_read.created_at == m.created_at);
assert(m_read.resolution == "2mp");
assert(m_read.interval_sec == 5);
assert(m_read.fps == 24);
assert(m_read.frame_count == 2);
assert(m_read.status == "recording");
// Add 2 valid frames to sess.work_dir and create an empty .tl_work_ dir
write_bytes(sess.work_dir + "/frame_0001.jpg", "jpg1");
write_bytes(sess.work_dir + "/frame_0002.jpg", "jpg2");
const std::string empty_work = out_dir + "/.tl_work_20260101_000000";
assert(cz::mkdir_p(empty_work));
cz::TimelapseManifest empty_m = m;
empty_m.session_id = "20260101_000000";
empty_m.work_dir = empty_work;
empty_m.frame_count = 0;
assert(cz::write_timelapse_manifest(empty_work, empty_m));
const std::vector<cz::TimelapseManifest> orphans = cz::scan_orphaned_timelapses(out_dir);
assert(orphans.size() == 1);
assert(orphans[0].session_id == sess.session_id);
assert(orphans[0].work_dir == sess.work_dir);
assert(orphans[0].frame_count == 2);
}
} // namespace
int main() {
test_theme_tokens_and_toggle();
test_fb_blit_rgb565_argb32_and_bounds();
test_config_defaults_roundtrip_and_corrupt_fallback();
test_sync_safe_staging_collision_storage_floor_and_manifest();
std::cout << "test_config_and_storage: all tests passed\n";
return 0;
}