feat(app): add backlight auto-dim, timelapse engine, gallery model, and video player

This commit is contained in:
2026-11-19 14:17:11 -05:00
parent 3c4a870e70
commit ff1a27e25b
10 changed files with 4202 additions and 0 deletions

View File

@@ -37,6 +37,10 @@ add_library(czcamera_core STATIC
src/jpeg_pipeline.cpp
src/subprocess_backend.cpp
src/sim_backend.cpp
src/backlight.cpp
src/timelapse_engine.cpp
src/gallery_model.cpp
src/video_player.cpp
)
target_include_directories(czcamera_core
@@ -103,4 +107,9 @@ if(CZ_BUILD_TESTS)
)
target_link_libraries(test_backend_protocol PRIVATE czcamera_core)
add_test(NAME test_backend_protocol COMMAND test_backend_protocol)
add_executable(test_timelapse_and_gallery tests/test_timelapse_and_gallery.cpp)
target_compile_options(test_timelapse_and_gallery PRIVATE -Wall -Wextra -Wpedantic)
target_link_libraries(test_timelapse_and_gallery PRIVATE czcamera_core)
add_test(NAME test_timelapse_and_gallery COMMAND test_timelapse_and_gallery)
endif()

212
app/src/backlight.cpp Normal file
View File

@@ -0,0 +1,212 @@
#include "backlight.hpp"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstring>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
namespace cz {
namespace {
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;
}
std::string trim_ascii_ws(const std::string& s) {
size_t start = 0;
while (start < s.size() &&
std::isspace(static_cast<unsigned char>(s[start]))) {
++start;
}
size_t end = s.size();
while (end > start &&
std::isspace(static_cast<unsigned char>(s[end - 1]))) {
--end;
}
return s.substr(start, end - start);
}
} // namespace
BacklightController::BacklightController(const std::string& sysfs_root)
: sysfs_root_(sysfs_root) {
std::lock_guard<std::mutex> lock(mutex_);
probe_sysfs_locked();
}
BacklightController::~BacklightController() { restore(); }
void BacklightController::probe_sysfs_locked() {
has_hardware_backlight_ = false;
brightness_path_.clear();
max_brightness_path_.clear();
if (sysfs_root_.empty()) {
return;
}
DIR* dir = ::opendir(sysfs_root_.c_str());
if (!dir) {
return;
}
std::vector<std::string> entries;
struct dirent* ent = nullptr;
while ((ent = ::readdir(dir)) != nullptr) {
const std::string name(ent->d_name);
if (name.empty() || name[0] == '.') {
continue;
}
entries.push_back(name);
}
::closedir(dir);
std::sort(entries.begin(), entries.end());
for (const auto& entry : entries) {
const std::string dev_dir = join_path(sysfs_root_, entry);
struct stat dir_st {};
if (::stat(dev_dir.c_str(), &dir_st) != 0 || !S_ISDIR(dir_st.st_mode)) {
continue;
}
const std::string b_path = join_path(dev_dir, "brightness");
struct stat b_st {};
if (::stat(b_path.c_str(), &b_st) != 0 || !S_ISREG(b_st.st_mode)) {
continue;
}
if ((b_st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) == 0) {
continue;
}
const int fd = ::open(b_path.c_str(), O_RDWR);
if (fd >= 0) {
::close(fd);
brightness_path_ = b_path;
max_brightness_path_ = join_path(dev_dir, "max_brightness");
has_hardware_backlight_ = true;
return;
}
}
}
bool BacklightController::read_trimmed_file_locked(const std::string& path,
std::string& out_value) const {
out_value.clear();
if (path.empty()) {
return false;
}
const int fd = ::open(path.c_str(), O_RDONLY);
if (fd < 0) {
return false;
}
char buf[64];
std::string raw;
while (true) {
const ssize_t n = ::read(fd, buf, sizeof(buf));
if (n > 0) {
raw.append(buf, static_cast<size_t>(n));
if (raw.size() >= 256) {
break;
}
continue;
}
if (n == 0) {
break;
}
if (errno == EINTR) {
continue;
}
::close(fd);
return false;
}
::close(fd);
out_value = trim_ascii_ws(raw);
return !out_value.empty();
}
bool BacklightController::write_file_locked(const std::string& path,
const std::string& value) const {
if (path.empty()) {
return false;
}
const int fd = ::open(path.c_str(), O_WRONLY | O_TRUNC);
if (fd < 0) {
return false;
}
size_t off = 0;
while (off < value.size()) {
const ssize_t w = ::write(fd, value.data() + off, value.size() - off);
if (w > 0) {
off += static_cast<size_t>(w);
continue;
}
if (w < 0 && errno == EINTR) {
continue;
}
::close(fd);
return false;
}
::close(fd);
return true;
}
bool BacklightController::dim() {
std::lock_guard<std::mutex> lock(mutex_);
if (dimmed_) {
return true;
}
bool ok = true;
if (has_hardware_backlight_) {
std::string cur;
if (!read_trimmed_file_locked(brightness_path_, cur)) {
if (!read_trimmed_file_locked(max_brightness_path_, cur)) {
cur = "128";
}
}
saved_brightness_ = cur;
ok = write_file_locked(brightness_path_, "0");
}
dimmed_ = true;
return ok;
}
bool BacklightController::restore() {
std::lock_guard<std::mutex> lock(mutex_);
if (!dimmed_) {
return true;
}
bool ok = true;
if (has_hardware_backlight_ && !saved_brightness_.empty()) {
ok = write_file_locked(brightness_path_, saved_brightness_);
}
dimmed_ = false;
saved_brightness_.clear();
return ok;
}
bool BacklightController::is_dimmed() const {
std::lock_guard<std::mutex> lock(mutex_);
return dimmed_;
}
bool BacklightController::has_hardware_backlight() const {
std::lock_guard<std::mutex> lock(mutex_);
return has_hardware_backlight_;
}
} // namespace cz

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

@@ -0,0 +1,38 @@
#pragma once
#include <mutex>
#include <string>
namespace cz {
class BacklightController {
public:
explicit BacklightController(
const std::string& sysfs_root = "/sys/class/backlight");
~BacklightController();
BacklightController(const BacklightController&) = delete;
BacklightController& operator=(const BacklightController&) = delete;
bool dim();
bool restore();
bool is_dimmed() const;
bool has_hardware_backlight() const;
private:
void probe_sysfs_locked();
bool read_trimmed_file_locked(const std::string& path,
std::string& out_value) const;
bool write_file_locked(const std::string& path,
const std::string& value) const;
mutable std::mutex mutex_;
std::string sysfs_root_;
std::string brightness_path_;
std::string max_brightness_path_;
std::string saved_brightness_;
bool has_hardware_backlight_ = false;
bool dimmed_ = false;
};
} // namespace cz

542
app/src/gallery_model.cpp Normal file
View File

@@ -0,0 +1,542 @@
#include "gallery_model.hpp"
#include "config.hpp"
#include "video_player.hpp"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <csetjmp>
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <filesystem>
#include <jpeglib.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
namespace fs = std::filesystem;
namespace cz {
namespace {
struct SortableEntry {
GalleryItem item;
int64_t mtime_nsec = 0;
};
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;
}
void extract_mtime(const struct stat& st, int64_t& sec, int64_t& nsec) {
#ifdef __APPLE__
sec = static_cast<int64_t>(st.st_mtimespec.tv_sec);
nsec = static_cast<int64_t>(st.st_mtimespec.tv_nsec);
#else
sec = static_cast<int64_t>(st.st_mtim.tv_sec);
nsec = static_cast<int64_t>(st.st_mtim.tv_nsec);
#endif
}
bool is_jpeg_name(const std::string& name) {
return media_detail::ends_with_ci(name, ".jpg") ||
media_detail::ends_with_ci(name, ".jpeg");
}
bool is_staging_name(const std::string& name) {
return name.empty() || name[0] == '.' ||
media_detail::ends_with_ci(name, ".tmp") ||
media_detail::ends_with_ci(name, ".part");
}
struct HeaderJpegErr {
jpeg_error_mgr pub;
jmp_buf env;
};
void hdr_err_exit(j_common_ptr cinfo) {
auto* e = reinterpret_cast<HeaderJpegErr*>(cinfo->err);
longjmp(e->env, 1);
}
void hdr_output_msg(j_common_ptr /*cinfo*/) {}
bool probe_jpeg_dimensions(const std::string& path, int& out_w, int& out_h) {
out_w = 0;
out_h = 0;
FILE* fp = std::fopen(path.c_str(), "rb");
if (!fp) return false;
jpeg_decompress_struct cinfo{};
HeaderJpegErr jerr{};
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = hdr_err_exit;
jerr.pub.output_message = hdr_output_msg;
if (setjmp(jerr.env) != 0) {
jpeg_destroy_decompress(&cinfo);
std::fclose(fp);
return false;
}
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, fp);
if (jpeg_read_header(&cinfo, TRUE) == JPEG_HEADER_OK) {
out_w = static_cast<int>(cinfo.image_width);
out_h = static_cast<int>(cinfo.image_height);
}
jpeg_destroy_decompress(&cinfo);
std::fclose(fp);
return out_w > 0 && out_h > 0;
}
bool decode_scaled_jpeg_preview(const std::string& path,
int max_w,
int max_h,
RgbImage& out,
std::string& out_err) {
RgbImage decoded;
if (!decode_jpeg_scaled_rgb24(path, max_w, max_h, decoded, out_err)) {
return false;
}
if (decoded.width <= max_w && decoded.height <= max_h) {
out = std::move(decoded);
return true;
}
if (!media_detail::aspect_scale_rgb24(
decoded.rgb24.data(), decoded.width, decoded.height, max_w, max_h,
out.rgb24, out.width, out.height)) {
out_err = "failed to scale JPEG preview";
return false;
}
return true;
}
bool extract_video_poster_rgb24(const std::string& mp4_path,
int target_w,
int target_h,
RgbImage& out,
std::string& out_err) {
out = RgbImage{};
out_err.clear();
const std::string ffmpeg = media_detail::resolve_executable("ffmpeg");
if (ffmpeg.empty()) {
out_err = "ffmpeg executable not found";
return false;
}
media_detail::ignore_sigpipe_once();
std::vector<std::string> args = {
ffmpeg,
"-nostdin",
"-loglevel",
"error",
"-i",
mp4_path,
"-frames:v",
"1",
"-vf",
"scale=" + std::to_string(target_w) + ":" + std::to_string(target_h),
"-f",
"rawvideo",
"-pix_fmt",
"rgb24",
"-",
};
pid_t pid = -1;
int stdout_fd = -1;
if (!media_detail::spawn_stdout_process(ffmpeg, args, pid, stdout_fd)) {
out_err = "failed to spawn ffmpeg for poster frame";
return false;
}
const size_t expected =
static_cast<size_t>(target_w) * static_cast<size_t>(target_h) * 3u;
std::vector<uint8_t> buf(expected);
size_t off = 0;
const auto dl = std::chrono::steady_clock::now() + std::chrono::seconds(4);
while (off < expected && std::chrono::steady_clock::now() < dl) {
pollfd pfd{stdout_fd, POLLIN, 0};
const int rc = ::poll(&pfd, 1, 100);
if (rc < 0) {
if (errno == EINTR) continue;
break;
}
if (pfd.revents & (POLLIN | POLLHUP | POLLERR)) {
bool hit_eof = false;
while (off < expected) {
const ssize_t r = ::read(stdout_fd, buf.data() + off, expected - off);
if (r > 0) {
off += static_cast<size_t>(r);
continue;
}
if (r == 0) {
hit_eof = true;
break;
}
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
hit_eof = true;
break;
}
if (hit_eof) break;
}
}
::close(stdout_fd);
int status = 0;
if (!media_detail::reap_pid_timeout(pid, 500, &status)) {
pid_t tmp = pid;
media_detail::kill_and_reap(tmp);
out_err = "ffmpeg poster decode timed out";
return false;
}
if (off != expected) {
out_err = "failed to decode video poster frame";
return false;
}
out.width = target_w;
out.height = target_h;
out.rgb24 = std::move(buf);
return true;
}
void summarize_timelapse_folder(const std::string& dir_path,
int& out_count,
uint64_t& out_bytes) {
out_count = 0;
out_bytes = 0;
DIR* d = ::opendir(dir_path.c_str());
if (!d) return;
struct dirent* ent = nullptr;
while ((ent = ::readdir(d)) != nullptr) {
const std::string name(ent->d_name);
if (is_staging_name(name) || !is_jpeg_name(name)) {
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) {
++out_count;
out_bytes += static_cast<uint64_t>(st.st_size);
}
}
::closedir(d);
}
std::string find_first_timelapse_frame(const std::string& dir_path) {
DIR* d = ::opendir(dir_path.c_str());
if (!d) return "";
std::vector<std::string> names;
struct dirent* ent = nullptr;
while ((ent = ::readdir(d)) != nullptr) {
const std::string name(ent->d_name);
if (is_staging_name(name) || !is_jpeg_name(name)) {
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) {
names.push_back(name);
}
}
::closedir(d);
if (names.empty()) return "";
std::sort(names.begin(), names.end());
return join_path(dir_path, names.front());
}
} // namespace
bool GalleryStore::refresh(const std::string& output_dir) {
const std::string expanded = expand_user_path(output_dir);
struct stat st {};
if (expanded.empty() || ::stat(expanded.c_str(), &st) != 0 ||
!S_ISDIR(st.st_mode)) {
items_.clear();
in_session_ = false;
session_dir_.clear();
session_name_.clear();
root_dir_.clear();
return false;
}
if (in_session_ && expanded == root_dir_) {
struct stat sst {};
if (::stat(session_dir_.c_str(), &sst) == 0 && S_ISDIR(sst.st_mode)) {
return scan_session_dir();
}
in_session_ = false;
session_dir_.clear();
session_name_.clear();
}
root_dir_ = expanded;
in_session_ = false;
session_dir_.clear();
session_name_.clear();
return scan_root_dir();
}
bool GalleryStore::scan_root_dir() {
items_.clear();
DIR* d = ::opendir(root_dir_.c_str());
if (!d) {
return false;
}
std::vector<SortableEntry> found;
struct dirent* ent = nullptr;
while ((ent = ::readdir(d)) != nullptr) {
const std::string name(ent->d_name);
if (is_staging_name(name)) {
continue;
}
const std::string full = join_path(root_dir_, name);
struct stat st {};
if (::stat(full.c_str(), &st) != 0) {
continue;
}
if (S_ISREG(st.st_mode)) {
if (is_jpeg_name(name)) {
SortableEntry se;
se.item.type = GalleryItemType::Photo;
se.item.abs_path = full;
se.item.filename = name;
se.item.size_bytes = static_cast<uint64_t>(std::max<off_t>(0, st.st_size));
extract_mtime(st, se.item.mtime_epoch, se.mtime_nsec);
found.push_back(std::move(se));
} else if (media_detail::ends_with_ci(name, ".mp4")) {
SortableEntry se;
se.item.type = GalleryItemType::Video;
se.item.abs_path = full;
se.item.filename = name;
se.item.size_bytes = static_cast<uint64_t>(std::max<off_t>(0, st.st_size));
extract_mtime(st, se.item.mtime_epoch, se.mtime_nsec);
found.push_back(std::move(se));
}
} else if (S_ISDIR(st.st_mode) && name.rfind("TL_", 0) == 0) {
int count = 0;
uint64_t total_bytes = 0;
summarize_timelapse_folder(full, count, total_bytes);
SortableEntry se;
se.item.type = GalleryItemType::TimelapseFolder;
se.item.abs_path = full;
se.item.filename = name;
se.item.photo_count = count;
se.item.size_bytes = total_bytes;
extract_mtime(st, se.item.mtime_epoch, se.mtime_nsec);
found.push_back(std::move(se));
}
}
::closedir(d);
std::sort(found.begin(), found.end(),
[](const SortableEntry& a, const SortableEntry& b) {
if (a.item.mtime_epoch != b.item.mtime_epoch) {
return a.item.mtime_epoch > b.item.mtime_epoch;
}
if (a.mtime_nsec != b.mtime_nsec) {
return a.mtime_nsec > b.mtime_nsec;
}
return a.item.filename > b.item.filename;
});
items_.reserve(found.size());
for (auto& se : found) {
items_.push_back(std::move(se.item));
}
return true;
}
bool GalleryStore::scan_session_dir() {
items_.clear();
DIR* d = ::opendir(session_dir_.c_str());
if (!d) {
return false;
}
std::vector<GalleryItem> found;
struct dirent* ent = nullptr;
while ((ent = ::readdir(d)) != nullptr) {
const std::string name(ent->d_name);
if (is_staging_name(name) || !is_jpeg_name(name)) {
continue;
}
const std::string full = join_path(session_dir_, name);
struct stat st {};
if (::stat(full.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
continue;
}
GalleryItem item;
item.type = GalleryItemType::Photo;
item.abs_path = full;
item.filename = name;
item.size_bytes = static_cast<uint64_t>(std::max<off_t>(0, st.st_size));
int64_t nsec_unused = 0;
extract_mtime(st, item.mtime_epoch, nsec_unused);
found.push_back(std::move(item));
}
::closedir(d);
std::sort(found.begin(), found.end(),
[](const GalleryItem& a, const GalleryItem& b) {
return a.filename < b.filename;
});
items_ = std::move(found);
return true;
}
bool GalleryStore::enter_session(int index) {
if (in_session_ || index < 0 || index >= static_cast<int>(items_.size())) {
return false;
}
const GalleryItem& target = items_[static_cast<size_t>(index)];
if (target.type != GalleryItemType::TimelapseFolder) {
return false;
}
in_session_ = true;
session_dir_ = target.abs_path;
session_name_ = target.filename;
return scan_session_dir();
}
bool GalleryStore::exit_session() {
if (!in_session_) {
return false;
}
in_session_ = false;
session_dir_.clear();
session_name_.clear();
return scan_root_dir();
}
bool GalleryStore::in_session() const { return in_session_; }
std::string GalleryStore::session_name() const { return session_name_; }
const std::vector<GalleryItem>& GalleryStore::items() const { return items_; }
bool GalleryStore::probe_video_meta(GalleryItem& item) {
if (item.type != GalleryItemType::Video || item.abs_path.empty()) {
return false;
}
const media_detail::VideoProbeResult probe =
media_detail::probe_video_file(item.abs_path);
if (!probe.ok) {
return false;
}
item.duration_sec = probe.duration_sec;
item.width = probe.width;
item.height = probe.height;
return true;
}
bool GalleryStore::load_preview_rgb24(int index,
int max_w,
int max_h,
RgbImage& out,
std::string& out_err) {
out = RgbImage{};
out_err.clear();
if (index < 0 || index >= static_cast<int>(items_.size())) {
out_err = "gallery index out of range";
return false;
}
if (max_w <= 0 || max_h <= 0) {
out_err = "invalid preview dimensions";
return false;
}
GalleryItem& item = items_[static_cast<size_t>(index)];
if (item.type == GalleryItemType::Photo) {
if (item.width <= 0 || item.height <= 0) {
int w = 0;
int h = 0;
if (probe_jpeg_dimensions(item.abs_path, w, h)) {
item.width = w;
item.height = h;
}
}
return decode_scaled_jpeg_preview(item.abs_path, max_w, max_h, out,
out_err);
}
if (item.type == GalleryItemType::TimelapseFolder) {
const std::string first_frame = find_first_timelapse_frame(item.abs_path);
if (first_frame.empty()) {
out_err = "timelapse folder has no valid frames";
return false;
}
return decode_scaled_jpeg_preview(first_frame, max_w, max_h, out, out_err);
}
// GalleryItemType::Video
if (item.width <= 0 || item.height <= 0) {
if (!probe_video_meta(item)) {
out_err = "failed to probe video metadata";
return false;
}
}
int target_w = 0;
int target_h = 0;
if (!media_detail::compute_fit_dimensions(item.width, item.height, max_w,
max_h, target_w, target_h)) {
out_err = "invalid video dimensions";
return false;
}
return extract_video_poster_rgb24(item.abs_path, target_w, target_h, out,
out_err);
}
bool GalleryStore::delete_item(int index, std::string& out_err) {
out_err.clear();
if (index < 0 || index >= static_cast<int>(items_.size())) {
out_err = "gallery index out of range";
return false;
}
const GalleryItem target = items_[static_cast<size_t>(index)];
if (target.abs_path.empty() || target.abs_path == "/" ||
target.abs_path == root_dir_) {
out_err = "refusing unsafe delete path";
return false;
}
std::error_code ec;
if (target.type == GalleryItemType::TimelapseFolder) {
fs::remove_all(target.abs_path, ec);
} else {
fs::remove(target.abs_path, ec);
}
if (ec) {
out_err = "delete failed: " + ec.message();
return false;
}
items_.erase(items_.begin() + index);
return true;
}
} // namespace cz

58
app/src/gallery_model.hpp Normal file
View File

@@ -0,0 +1,58 @@
#pragma once
#include "jpeg_pipeline.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace cz {
enum class GalleryItemType {
Photo,
Video,
TimelapseFolder,
};
struct GalleryItem {
GalleryItemType type = GalleryItemType::Photo;
std::string abs_path;
std::string filename;
int64_t mtime_epoch = 0;
uint64_t size_bytes = 0;
int photo_count = 0;
double duration_sec = 0.0;
int width = 0;
int height = 0;
};
class GalleryStore {
public:
bool refresh(const std::string& output_dir);
bool enter_session(int index);
bool exit_session();
bool in_session() const;
std::string session_name() const;
const std::vector<GalleryItem>& items() const;
bool load_preview_rgb24(int index,
int max_w,
int max_h,
RgbImage& out,
std::string& out_err);
bool probe_video_meta(GalleryItem& item);
bool delete_item(int index, std::string& out_err);
private:
bool scan_root_dir();
bool scan_session_dir();
std::string root_dir_;
std::string session_dir_;
std::string session_name_;
bool in_session_ = false;
std::vector<GalleryItem> items_;
};
} // namespace cz

View File

@@ -0,0 +1,967 @@
#include "timelapse_engine.hpp"
#include "video_player.hpp"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <filesystem>
#include <poll.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
namespace fs = std::filesystem;
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;
}
std::string parent_dir_of(const std::string& path) {
std::string p = path;
while (p.size() > 1 && p.back() == '/') {
p.pop_back();
}
const size_t slash = p.find_last_of('/');
if (slash == std::string::npos) {
return ".";
}
if (slash == 0) {
return "/";
}
return p.substr(0, slash);
}
std::string current_iso8601_utc() {
const std::time_t now = std::time(nullptr);
struct tm tm_utc {};
::gmtime_r(&now, &tm_utc);
char buf[32];
std::snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02dZ",
tm_utc.tm_year + 1900, tm_utc.tm_mon + 1, tm_utc.tm_mday,
tm_utc.tm_hour, tm_utc.tm_min, tm_utc.tm_sec);
return std::string(buf);
}
void resolution_dimensions(const std::string& resolution, int& out_w, int& out_h) {
const std::string res = to_lower_ascii(resolution);
if (res == "8mp") {
out_w = 3280;
out_h = 2464;
} else if (res == "1080p") {
out_w = 1920;
out_h = 1080;
} else {
out_w = 1640;
out_h = 1232;
}
}
int count_valid_jpegs(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 (!media_detail::ends_with_ci(name, ".jpg") &&
!media_detail::ends_with_ci(name, ".jpeg")) {
continue;
}
const std::string full = 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;
}
void set_cloexec(int fd) {
if (fd < 0) return;
const int flags = ::fcntl(fd, F_GETFD);
if (flags >= 0) {
::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
}
void set_nonblocking(int fd) {
if (fd < 0) return;
const int flags = ::fcntl(fd, F_GETFL);
if (flags >= 0) {
::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
}
void close_fd_safe(int& fd) {
if (fd >= 0) {
::close(fd);
fd = -1;
}
}
void remove_silent(const std::string& path) {
if (path.empty()) return;
std::error_code ec;
fs::remove(path, ec);
}
} // namespace
TimelapseEngine::TimelapseEngine(ICameraBackend* backend) : backend_(backend) {
media_detail::ignore_sigpipe_once();
}
TimelapseEngine::~TimelapseEngine() {
cancel_compile();
std::lock_guard<std::mutex> lock(mutex_);
state_.running = false;
}
void TimelapseEngine::set_backend(ICameraBackend* backend) {
std::lock_guard<std::mutex> lock(mutex_);
backend_ = backend;
}
std::vector<std::string> TimelapseEngine::build_compile_command(
const TimelapseSessionPaths& paths,
int fps,
const std::string& resolution,
bool use_hw_encoder) {
const int safe_fps = std::clamp(fps, 1, 120);
std::string input_pattern = paths.work_dir;
if (!input_pattern.empty() && input_pattern.back() != '/') {
input_pattern += '/';
}
input_pattern += "frame_%04d.jpg";
std::vector<std::string> args = {
"ffmpeg",
"-nostdin",
"-y",
"-framerate",
std::to_string(safe_fps),
"-start_number",
"1",
"-i",
input_pattern,
};
if (to_lower_ascii(resolution) == "8mp") {
args.push_back("-vf");
args.push_back("scale=1440:1080:flags=lanczos");
}
if (use_hw_encoder) {
args.push_back("-c:v");
args.push_back("h264_v4l2m2m");
args.push_back("-b:v");
args.push_back("6M");
args.push_back("-pix_fmt");
args.push_back("yuv420p");
} else {
args.push_back("-c:v");
args.push_back("libx264");
args.push_back("-preset");
args.push_back("veryfast");
args.push_back("-crf");
args.push_back("22");
args.push_back("-pix_fmt");
args.push_back("yuv420p");
}
args.push_back("-f");
args.push_back("mp4");
args.push_back("-movflags");
args.push_back("+faststart");
args.push_back("-loglevel");
args.push_back("error");
args.push_back("-progress");
args.push_back("pipe:1");
args.push_back(paths.mp4_tmp_path);
return args;
}
bool TimelapseEngine::start(const AppConfig& cfg, uint64_t now_ms) {
std::lock_guard<std::mutex> lock(mutex_);
if (state_.running || state_.compiling) {
state_.last_error = "Timelapse already active";
return false;
}
if (!backend_) {
state_.last_error = "No camera backend available";
return false;
}
const BackendHealth health = backend_->status();
if (!health.ready || health.paused) {
state_.last_error = "Camera backend is not ready";
return false;
}
const std::string out_dir = expand_user_path(cfg.output_dir);
if (out_dir.empty() || !mkdir_p(out_dir)) {
state_.last_error = "Failed to prepare output directory";
return false;
}
if (!has_sufficient_storage(out_dir)) {
state_.last_error = "Insufficient storage (<100MB free)";
return false;
}
const bool is_photos = (to_lower_ascii(cfg.timelapse_output_mode) == "photos");
TimelapseSessionPaths paths = create_timelapse_session(out_dir, !is_photos);
if (is_photos) {
if (!mkdir_p(paths.photos_dir)) {
state_.last_error = "Failed to create timelapse folder";
return false;
}
} else {
if (!mkdir_p(paths.work_dir)) {
state_.last_error = "Failed to create timelapse work directory";
return false;
}
}
const std::string res =
cfg.timelapse_resolution.empty() ? "2mp" : to_lower_ascii(cfg.timelapse_resolution);
const int interval_sec = std::clamp(cfg.timelapse_interval_sec, 1, 3600);
const int fps = (cfg.timelapse_fps > 0) ? cfg.timelapse_fps : 24;
TimelapseManifest m;
m.session_id = paths.session_id;
m.work_dir = paths.work_dir;
m.created_at = current_iso8601_utc();
m.resolution = res;
m.interval_sec = interval_sec;
m.fps = fps;
m.frame_count = 0;
m.status = "recording";
if (!is_photos && !write_timelapse_manifest(paths.manifest_path, m)) {
std::error_code ec;
fs::remove_all(paths.work_dir, ec);
state_.last_error = "Failed to write timelapse manifest";
return false;
}
session_ = paths;
manifest_ = m;
output_dir_ = out_dir;
resolution_ = res;
start_ms_ = now_ms;
next_shot_ms_ = now_ms;
capturing_ = false;
stop_requested_ = false;
state_ = TimelapseState{};
state_.running = true;
state_.compiling = false;
state_.shots_taken = 0;
state_.stop_mode =
cfg.timelapse_stop_mode.empty() ? "manual" : to_lower_ascii(cfg.timelapse_stop_mode);
state_.stop_value = std::max(0, cfg.timelapse_stop_value);
state_.interval_sec = interval_sec;
state_.next_shot_in_sec = 0;
state_.elapsed_sec = 0;
state_.output_mode = is_photos ? "photos" : "video";
state_.needs_compile = false;
state_.stopped_by_low_storage = false;
return true;
}
void TimelapseEngine::finish_capture_locked() {
state_.running = false;
state_.next_shot_in_sec = 0;
if (state_.output_mode == "photos") {
state_.needs_compile = false;
if (state_.shots_taken > 0) {
state_.result_path = session_.photos_dir;
} else {
std::error_code ec;
fs::remove_all(session_.photos_dir, ec);
state_.result_path.clear();
}
} else {
if (state_.shots_taken > 0) {
state_.needs_compile = true;
manifest_.frame_count = state_.shots_taken;
manifest_.status = "stopped";
write_timelapse_manifest(session_.manifest_path, manifest_);
} else {
state_.needs_compile = false;
std::error_code ec;
fs::remove_all(session_.work_dir, ec);
state_.result_path.clear();
}
}
}
void TimelapseEngine::tick(uint64_t now_ms, const AppConfig& /*cfg*/) {
ICameraBackend* backend = nullptr;
StagedPaths frame_paths;
int cap_w = 1640;
int cap_h = 1232;
int next_idx = 1;
uint64_t clamped_now = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!state_.running || capturing_) {
return;
}
clamped_now = std::max(now_ms, start_ms_);
state_.elapsed_sec = static_cast<int>((clamped_now - start_ms_) / 1000ULL);
if (state_.stop_mode == "duration" && state_.stop_value > 0 &&
state_.elapsed_sec >= state_.stop_value) {
finish_capture_locked();
return;
}
if (clamped_now < next_shot_ms_) {
state_.next_shot_in_sec =
static_cast<int>((next_shot_ms_ - clamped_now + 999ULL) / 1000ULL);
return;
}
if (!has_sufficient_storage(output_dir_)) {
state_.stopped_by_low_storage = true;
state_.last_error = "Low storage (<100MB)";
finish_capture_locked();
return;
}
backend = backend_;
if (!backend) {
state_.last_error = "Camera backend unavailable";
finish_capture_locked();
return;
}
next_idx = state_.shots_taken + 1;
const std::string target_dir =
(state_.output_mode == "photos") ? session_.photos_dir : session_.work_dir;
frame_paths = next_timelapse_frame_paths(target_dir, next_idx);
resolution_dimensions(resolution_, cap_w, cap_h);
capturing_ = true;
}
const StillCaptureResult cap =
backend->capture_still(frame_paths.tmp_path, cap_w, cap_h);
std::lock_guard<std::mutex> lock(mutex_);
capturing_ = false;
if (!state_.running) {
remove_silent(frame_paths.tmp_path);
return;
}
if (!cap.ok) {
remove_silent(frame_paths.tmp_path);
state_.last_error =
cap.error.empty() ? "timelapse capture_still failed" : cap.error;
finish_capture_locked();
return;
}
std::string commit_err;
if (!commit_staged_file(frame_paths.tmp_path, frame_paths.final_path,
commit_err)) {
remove_silent(frame_paths.tmp_path);
state_.last_error = commit_err;
finish_capture_locked();
return;
}
state_.shots_taken = next_idx;
if (state_.output_mode == "video") {
manifest_.frame_count = state_.shots_taken;
write_timelapse_manifest(session_.manifest_path, manifest_);
}
const uint64_t interval_ms =
static_cast<uint64_t>(std::max(1, state_.interval_sec)) * 1000ULL;
next_shot_ms_ += interval_ms;
while (next_shot_ms_ <= clamped_now) {
next_shot_ms_ += interval_ms;
}
state_.next_shot_in_sec =
static_cast<int>((next_shot_ms_ - clamped_now + 999ULL) / 1000ULL);
if (stop_requested_ ||
(state_.stop_mode == "shots" && state_.stop_value > 0 &&
state_.shots_taken >= state_.stop_value)) {
finish_capture_locked();
}
}
void TimelapseEngine::request_stop() {
std::lock_guard<std::mutex> lock(mutex_);
if (!state_.running) {
return;
}
stop_requested_ = true;
if (!capturing_) {
finish_capture_locked();
}
}
bool TimelapseEngine::run_compile_attempt(
const std::string& ffmpeg_exe,
const TimelapseSessionPaths& paths,
int fps,
const std::string& resolution,
bool use_hw_encoder,
int total_frames,
const std::function<void(int, int)>& on_progress,
std::string& out_err) {
out_err.clear();
std::vector<std::string> args =
build_compile_command(paths, fps, resolution, use_hw_encoder);
if (!args.empty()) {
args[0] = ffmpeg_exe;
}
int out_pipe[2] = {-1, -1};
int err_pipe[2] = {-1, -1};
int wake_pipe[2] = {-1, -1};
if (::pipe(out_pipe) != 0) {
out_err = "pipe failed";
return false;
}
if (::pipe(err_pipe) != 0) {
::close(out_pipe[0]);
::close(out_pipe[1]);
out_err = "pipe failed";
return false;
}
if (::pipe(wake_pipe) != 0) {
::close(out_pipe[0]);
::close(out_pipe[1]);
::close(err_pipe[0]);
::close(err_pipe[1]);
out_err = "pipe failed";
return false;
}
set_cloexec(out_pipe[0]);
set_cloexec(err_pipe[0]);
set_cloexec(wake_pipe[0]);
set_cloexec(wake_pipe[1]);
set_nonblocking(out_pipe[0]);
set_nonblocking(err_pipe[0]);
set_nonblocking(wake_pipe[0]);
set_nonblocking(wake_pipe[1]);
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);
{
std::lock_guard<std::mutex> plock(compile_proc_mutex_);
if (cancel_compile_requested_) {
::close(out_pipe[0]);
::close(out_pipe[1]);
::close(err_pipe[0]);
::close(err_pipe[1]);
::close(wake_pipe[0]);
::close(wake_pipe[1]);
out_err = "Compile cancelled";
return false;
}
cancel_wake_r_ = wake_pipe[0];
cancel_wake_w_ = wake_pipe[1];
}
const pid_t pid = ::fork();
if (pid < 0) {
std::lock_guard<std::mutex> plock(compile_proc_mutex_);
cancel_wake_r_ = -1;
cancel_wake_w_ = -1;
::close(out_pipe[0]);
::close(out_pipe[1]);
::close(err_pipe[0]);
::close(err_pipe[1]);
::close(wake_pipe[0]);
::close(wake_pipe[1]);
out_err = "fork failed";
return false;
}
if (pid == 0) {
::close(out_pipe[0]);
::close(err_pipe[0]);
::close(wake_pipe[0]);
::close(wake_pipe[1]);
::dup2(out_pipe[1], STDOUT_FILENO);
::dup2(err_pipe[1], STDERR_FILENO);
if (out_pipe[1] > 2) ::close(out_pipe[1]);
if (err_pipe[1] > 2) ::close(err_pipe[1]);
const int devnull = ::open("/dev/null", O_RDONLY);
if (devnull >= 0) {
::dup2(devnull, STDIN_FILENO);
if (devnull > 2) ::close(devnull);
}
::execvp(ffmpeg_exe.c_str(), argv_ptrs.data());
_exit(127);
}
::close(out_pipe[1]);
::close(err_pipe[1]);
bool cancelled_before_register = false;
{
std::lock_guard<std::mutex> plock(compile_proc_mutex_);
compile_pid_ = pid;
if (cancel_compile_requested_) {
cancelled_before_register = true;
}
}
if (cancelled_before_register) {
::kill(pid, SIGTERM);
}
std::string out_line_buf;
std::string err_text;
bool out_open = true;
bool err_open = true;
bool cancelled = cancelled_before_register;
int last_reported = -1;
auto handle_progress_line = [&](const std::string& raw_line) {
std::string line = raw_line;
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
if (line.rfind("frame=", 0) == 0) {
const int frame_num = std::atoi(line.substr(6).c_str());
const int cur = std::clamp(frame_num, 0, total_frames);
if (cur != last_reported) {
last_reported = cur;
{
std::lock_guard<std::mutex> lock(mutex_);
state_.compile_current = cur;
state_.compile_total = total_frames;
state_.compile_progress =
total_frames > 0
? static_cast<float>(cur) / static_cast<float>(total_frames)
: 0.0f;
}
if (on_progress) {
on_progress(cur, total_frames);
}
}
} else if (line == "progress=end" && total_frames > 0 &&
last_reported < total_frames) {
last_reported = total_frames;
{
std::lock_guard<std::mutex> lock(mutex_);
state_.compile_current = total_frames;
state_.compile_total = total_frames;
state_.compile_progress = 1.0f;
}
if (on_progress) {
on_progress(total_frames, total_frames);
}
}
};
while (out_open || err_open) {
pollfd pfds[3]{};
nfds_t nfds = 0;
int out_idx = -1;
int err_idx = -1;
int wake_idx = -1;
if (out_open) {
out_idx = static_cast<int>(nfds);
pfds[nfds++] = {out_pipe[0], POLLIN, 0};
}
if (err_open) {
err_idx = static_cast<int>(nfds);
pfds[nfds++] = {err_pipe[0], POLLIN, 0};
}
wake_idx = static_cast<int>(nfds);
pfds[nfds++] = {wake_pipe[0], POLLIN, 0};
const int rc = ::poll(pfds, nfds, 250);
if (rc < 0) {
if (errno == EINTR) continue;
break;
}
if (wake_idx >= 0 && (pfds[wake_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
cancelled = true;
break;
}
if (out_idx >= 0 && (pfds[out_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
char buf[1024];
while (true) {
const ssize_t r = ::read(out_pipe[0], buf, sizeof(buf));
if (r > 0) {
out_line_buf.append(buf, static_cast<size_t>(r));
size_t nl = 0;
while ((nl = out_line_buf.find('\n')) != std::string::npos) {
const std::string line = out_line_buf.substr(0, nl);
out_line_buf.erase(0, nl + 1);
handle_progress_line(line);
}
continue;
}
if (r == 0) {
if (!out_line_buf.empty()) {
handle_progress_line(out_line_buf);
out_line_buf.clear();
}
out_open = false;
break;
}
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
out_open = false;
break;
}
}
if (err_idx >= 0 && (pfds[err_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
char buf[1024];
while (true) {
const ssize_t r = ::read(err_pipe[0], buf, sizeof(buf));
if (r > 0) {
if (err_text.size() < 8192) {
err_text.append(buf, static_cast<size_t>(r));
}
continue;
}
if (r == 0) {
err_open = false;
break;
}
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
err_open = false;
break;
}
}
}
::close(out_pipe[0]);
::close(err_pipe[0]);
int status = 0;
{
std::lock_guard<std::mutex> plock(compile_proc_mutex_);
if (cancel_compile_requested_) {
cancelled = true;
}
if (cancelled) {
media_detail::kill_and_reap(compile_pid_);
} else {
const pid_t active = compile_pid_;
compile_pid_ = -1;
if (!media_detail::reap_pid_timeout(active, 1000, &status)) {
pid_t tmp = active;
media_detail::kill_and_reap(tmp);
out_err = "ffmpeg compile timed out while exiting";
close_fd_safe(cancel_wake_r_);
close_fd_safe(cancel_wake_w_);
return false;
}
}
close_fd_safe(cancel_wake_r_);
close_fd_safe(cancel_wake_w_);
}
if (cancelled) {
out_err = "Compile cancelled";
return false;
}
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
while (!err_text.empty() &&
(err_text.back() == '\n' || err_text.back() == '\r')) {
err_text.pop_back();
}
out_err = err_text.empty() ? "ffmpeg exited with error" : err_text;
return false;
}
struct stat st {};
if (::stat(paths.mp4_tmp_path.c_str(), &st) != 0 || !S_ISREG(st.st_mode) ||
st.st_size <= 0) {
out_err = "compiled MP4 staging file missing or empty";
return false;
}
return true;
}
bool TimelapseEngine::compile_session(
const TimelapseSessionPaths& paths,
int fps,
const std::string& resolution,
std::function<void(int, int)> on_progress) {
std::lock_guard<std::mutex> compile_guard(compile_mutex_);
const int total_frames = count_valid_jpegs(paths.work_dir);
if (total_frames <= 0) {
std::lock_guard<std::mutex> lock(mutex_);
state_.compiling = false;
state_.last_error = "No valid timelapse frames found";
return false;
}
const std::string out_dir = parent_dir_of(paths.mp4_final_path);
if (!mkdir_p(out_dir) || !has_sufficient_storage(out_dir)) {
std::lock_guard<std::mutex> lock(mutex_);
state_.compiling = false;
state_.last_error = "Insufficient storage for MP4 compilation";
return false;
}
const std::string ffmpeg = media_detail::resolve_executable("ffmpeg");
if (ffmpeg.empty()) {
std::lock_guard<std::mutex> lock(mutex_);
state_.compiling = false;
state_.last_error = "ffmpeg executable not found";
return false;
}
{
std::lock_guard<std::mutex> lock(mutex_);
state_.compiling = true;
state_.compile_current = 0;
state_.compile_total = total_frames;
state_.compile_progress = 0.0f;
state_.last_error.clear();
}
{
std::lock_guard<std::mutex> plock(compile_proc_mutex_);
cancel_compile_requested_ = false;
}
std::string err;
bool ok = run_compile_attempt(ffmpeg, paths, fps, resolution, true,
total_frames, on_progress, err);
bool cancelled = false;
{
std::lock_guard<std::mutex> plock(compile_proc_mutex_);
cancelled = cancel_compile_requested_;
}
if (!ok && !cancelled) {
remove_silent(paths.mp4_tmp_path);
ok = run_compile_attempt(ffmpeg, paths, fps, resolution, false,
total_frames, on_progress, err);
std::lock_guard<std::mutex> plock(compile_proc_mutex_);
cancelled = cancel_compile_requested_;
}
if (!ok || cancelled) {
remove_silent(paths.mp4_tmp_path);
std::lock_guard<std::mutex> lock(mutex_);
state_.compiling = false;
state_.last_error = cancelled ? "Compile cancelled" : err;
return false;
}
std::string commit_err;
if (!commit_staged_file(paths.mp4_tmp_path, paths.mp4_final_path,
commit_err)) {
remove_silent(paths.mp4_tmp_path);
std::lock_guard<std::mutex> lock(mutex_);
state_.compiling = false;
state_.last_error = commit_err;
return false;
}
struct stat fin_st {};
if (::stat(paths.mp4_final_path.c_str(), &fin_st) != 0 ||
fin_st.st_size <= 0) {
std::lock_guard<std::mutex> lock(mutex_);
state_.compiling = false;
state_.last_error = "final compiled MP4 missing or empty";
return false;
}
std::error_code ec;
fs::remove_all(paths.work_dir, ec);
std::lock_guard<std::mutex> lock(mutex_);
state_.compiling = false;
state_.needs_compile = false;
state_.compile_current = total_frames;
state_.compile_total = total_frames;
state_.compile_progress = 1.0f;
state_.result_path = paths.mp4_final_path;
state_.last_error.clear();
return true;
}
void TimelapseEngine::cancel_compile() {
std::lock_guard<std::mutex> plock(compile_proc_mutex_);
cancel_compile_requested_ = true;
if (cancel_wake_w_ >= 0) {
const uint8_t b = 1;
const ssize_t ignored = ::write(cancel_wake_w_, &b, 1);
(void)ignored;
}
if (compile_pid_ > 0) {
::kill(compile_pid_, SIGTERM);
}
}
bool TimelapseEngine::recover_session(const TimelapseManifest& manifest,
RecoveryAction action,
std::string& out_msg) {
out_msg.clear();
if (manifest.work_dir.empty()) {
out_msg = "Invalid timelapse manifest work directory";
return false;
}
std::string work_dir = manifest.work_dir;
while (work_dir.size() > 1 && work_dir.back() == '/') {
work_dir.pop_back();
}
const std::string out_dir = parent_dir_of(work_dir);
std::string session_id = manifest.session_id;
if (session_id.empty()) {
const std::string base = fs::path(work_dir).filename().string();
if (base.rfind(".tl_work_", 0) == 0) {
session_id = base.substr(9);
} else {
session_id = "recovered";
}
}
TimelapseSessionPaths paths;
paths.session_id = session_id;
paths.work_dir = work_dir;
paths.photos_dir = out_dir + "/TL_" + session_id;
paths.manifest_path = work_dir + "/session.json";
paths.mp4_tmp_path = out_dir + "/.TL_" + session_id + ".mp4.part";
paths.mp4_final_path = out_dir + "/TL_" + session_id + ".mp4";
if (action == RecoveryAction::Discard) {
std::error_code ec;
fs::remove_all(work_dir, ec);
remove_silent(paths.mp4_tmp_path);
if (ec) {
out_msg = "Failed to discard work dir: " + ec.message();
return false;
}
out_msg = "Discarded timelapse " + session_id;
return true;
}
if (action == RecoveryAction::KeepPhotos) {
if (!mkdir_p(paths.photos_dir)) {
out_msg = "Failed to create destination folder";
return false;
}
std::error_code ec;
std::vector<fs::path> frames_to_move;
for (const auto& entry : fs::directory_iterator(work_dir, ec)) {
if (ec) {
out_msg = "Failed scanning work dir: " + ec.message();
return false;
}
const std::string fname = entry.path().filename().string();
if (fname.empty() || fname[0] == '.') {
continue;
}
if (!media_detail::ends_with_ci(fname, ".jpg") &&
!media_detail::ends_with_ci(fname, ".jpeg")) {
continue;
}
std::error_code file_ec;
if (!entry.is_regular_file(file_ec) || file_ec) {
continue;
}
const uintmax_t fsize = entry.file_size(file_ec);
if (file_ec || fsize == 0) {
continue;
}
frames_to_move.push_back(entry.path());
}
int moved = 0;
for (const auto& src_path : frames_to_move) {
const std::string fname = src_path.filename().string();
const fs::path dst = fs::path(paths.photos_dir) / fname;
fs::rename(src_path, dst, ec);
if (ec) {
out_msg = "Failed moving frame " + fname + ": " + ec.message();
return false;
}
++moved;
}
fs::remove_all(work_dir, ec);
remove_silent(paths.mp4_tmp_path);
if (moved <= 0) {
fs::remove_all(paths.photos_dir, ec);
out_msg = "No valid frames found in timelapse";
return false;
}
{
std::lock_guard<std::mutex> lock(mutex_);
state_.result_path = paths.photos_dir;
}
out_msg = "Saved " + std::to_string(moved) + " photos to TL_" + session_id;
return true;
}
// RecoveryAction::Compile
const int fps = (manifest.fps > 0) ? manifest.fps : 24;
const std::string res =
manifest.resolution.empty() ? "2mp" : manifest.resolution;
if (!compile_session(paths, fps, res)) {
out_msg = state().last_error;
return false;
}
out_msg = "Compiled TL_" + session_id + ".mp4";
return true;
}
TimelapseState TimelapseEngine::state() const {
std::lock_guard<std::mutex> lock(mutex_);
return state_;
}
TimelapseSessionPaths TimelapseEngine::session_paths() const {
std::lock_guard<std::mutex> lock(mutex_);
return session_;
}
} // namespace cz

View File

@@ -0,0 +1,106 @@
#pragma once
#include "camera_backend.hpp"
#include "config.hpp"
#include "storage.hpp"
#include <cstdint>
#include <functional>
#include <mutex>
#include <string>
#include <sys/types.h>
#include <vector>
namespace cz {
enum class RecoveryAction {
Compile,
KeepPhotos,
Discard,
};
struct TimelapseState {
bool running = false;
bool compiling = false;
int shots_taken = 0;
std::string stop_mode = "manual";
int stop_value = 0;
int interval_sec = 5;
int next_shot_in_sec = 0;
int elapsed_sec = 0;
int compile_current = 0;
int compile_total = 0;
float compile_progress = 0.0f;
std::string last_error;
std::string result_path;
std::string output_mode = "video";
bool needs_compile = false;
bool stopped_by_low_storage = false;
};
class TimelapseEngine {
public:
explicit TimelapseEngine(ICameraBackend* backend = nullptr);
~TimelapseEngine();
TimelapseEngine(const TimelapseEngine&) = delete;
TimelapseEngine& operator=(const TimelapseEngine&) = delete;
void set_backend(ICameraBackend* backend);
bool start(const AppConfig& cfg, uint64_t now_ms);
void tick(uint64_t now_ms, const AppConfig& cfg);
void request_stop();
bool compile_session(const TimelapseSessionPaths& paths,
int fps,
const std::string& resolution,
std::function<void(int, int)> on_progress = nullptr);
void cancel_compile();
bool recover_session(const TimelapseManifest& manifest,
RecoveryAction action,
std::string& out_msg);
TimelapseState state() const;
TimelapseSessionPaths session_paths() const;
static std::vector<std::string> build_compile_command(
const TimelapseSessionPaths& paths,
int fps,
const std::string& resolution,
bool use_hw_encoder);
private:
void finish_capture_locked();
bool run_compile_attempt(const std::string& ffmpeg_exe,
const TimelapseSessionPaths& paths,
int fps,
const std::string& resolution,
bool use_hw_encoder,
int total_frames,
const std::function<void(int, int)>& on_progress,
std::string& out_err);
mutable std::mutex mutex_;
std::mutex compile_mutex_;
std::mutex compile_proc_mutex_;
ICameraBackend* backend_ = nullptr;
TimelapseState state_;
TimelapseSessionPaths session_;
TimelapseManifest manifest_;
std::string output_dir_;
std::string resolution_ = "2mp";
uint64_t start_ms_ = 0;
uint64_t next_shot_ms_ = 0;
bool capturing_ = false;
bool stop_requested_ = false;
bool cancel_compile_requested_ = false;
pid_t compile_pid_ = -1;
int cancel_wake_r_ = -1;
int cancel_wake_w_ = -1;
};
} // namespace cz

1372
app/src/video_player.cpp Normal file

File diff suppressed because it is too large Load Diff

144
app/src/video_player.hpp Normal file
View File

@@ -0,0 +1,144 @@
#pragma once
#include "camera_backend.hpp"
#include <condition_variable>
#include <cstdint>
#include <functional>
#include <mutex>
#include <string>
#include <sys/types.h>
#include <thread>
#include <vector>
namespace cz {
namespace media_detail {
struct VideoProbeResult {
bool ok = false;
double duration_sec = 0.0;
double fps = 24.0;
int width = 0;
int height = 0;
bool has_audio = false;
std::string error;
};
void ignore_sigpipe_once();
std::string resolve_executable(const std::string& name);
bool ends_with_ci(const std::string& s, const std::string& suffix);
bool spawn_stdout_process(const std::string& exe,
const std::vector<std::string>& args,
pid_t& out_pid,
int& out_stdout_fd);
bool reap_pid_timeout(pid_t pid, int timeout_ms, int* out_status = nullptr);
void kill_and_reap(pid_t& pid);
VideoProbeResult probe_video_file(const std::string& path);
bool compute_fit_dimensions(int src_w,
int src_h,
int max_w,
int max_h,
int& out_w,
int& out_h);
bool aspect_scale_rgb24(const uint8_t* src,
int src_w,
int src_h,
int max_w,
int max_h,
std::vector<uint8_t>& out_rgb,
int& out_w,
int& out_h);
bool read_exact_with_wake(int fd,
int wake_fd,
uint8_t* dst,
size_t n,
bool& out_woken,
bool& out_eof);
} // namespace media_detail
struct VideoPlayerState {
bool stopped = true;
bool playing = false;
bool paused = false;
bool muted = false;
bool eof = false;
double position_sec = 0.0;
double duration_sec = 0.0;
int width = 0;
int height = 0;
std::string error;
bool has_audio = false;
};
class VideoPlayer {
public:
VideoPlayer();
~VideoPlayer();
VideoPlayer(const VideoPlayer&) = delete;
VideoPlayer& operator=(const VideoPlayer&) = delete;
bool open(const std::string& mp4_path, int max_w, int max_h);
bool play(bool enable_audio = true);
void pause();
void toggle_mute();
bool seek_delta(double delta_sec);
bool poll_frame(PreviewFrame& out_frame);
void set_pcm_sink(std::function<void(const int16_t*, size_t)> sink);
void stop();
VideoPlayerState state() const;
private:
void stop_workers_locked_ctrl();
bool start_playback_locked_ctrl(double start_pos_sec, bool want_audio);
bool start_audio_worker_locked_ctrl(double start_pos_sec);
void stop_audio_worker_locked_ctrl();
void video_worker_loop(double start_pos_sec,
int frame_w,
int frame_h,
double fps,
int stdout_fd,
int wake_fd,
pid_t child_pid);
void audio_worker_pcm_loop(double start_pos_sec,
int stdout_fd,
int wake_fd,
pid_t child_pid,
std::function<void(const int16_t*, size_t)> sink);
void audio_worker_aplay_loop(int wake_fd, pid_t ffmpeg_pid, pid_t aplay_pid);
mutable std::mutex control_mutex_;
mutable std::mutex state_mutex_;
mutable std::mutex frame_mutex_;
std::mutex proc_mutex_;
std::condition_variable pace_cv_;
std::string mp4_path_;
int max_w_ = 226;
int max_h_ = 128;
double fps_ = 24.0;
bool opened_ = false;
VideoPlayerState state_;
std::function<void(const int16_t*, size_t)> pcm_sink_;
PreviewFrame latest_frame_;
uint64_t seq_counter_ = 0;
uint64_t last_polled_seq_ = 0;
bool workers_stop_ = false;
bool audio_stop_ = false;
int video_wake_r_ = -1;
int video_wake_w_ = -1;
int audio_wake_r_ = -1;
int audio_wake_w_ = -1;
pid_t video_pid_ = -1;
pid_t audio_ffmpeg_pid_ = -1;
pid_t aplay_pid_ = -1;
std::thread video_thread_;
std::thread audio_thread_;
};
} // namespace cz

View File

@@ -0,0 +1,754 @@
#include "backlight.hpp"
#include "config.hpp"
#include "gallery_model.hpp"
#include "jpeg_pipeline.hpp"
#include "sim_backend.hpp"
#include "storage.hpp"
#include "timelapse_engine.hpp"
#include "video_player.hpp"
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cerrno>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#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_t5_" + 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_text_file(const std::string& path, const std::string& content) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
assert(out.is_open());
out.write(content.data(), static_cast<std::streamsize>(content.size()));
out.close();
assert(out.good());
}
std::string read_text_file(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>());
}
bool create_sample_jpeg(const std::string& path, int w, int h, uint8_t seed) {
std::vector<uint8_t> rgb(static_cast<size_t>(w) * static_cast<size_t>(h) * 3u);
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
const size_t idx = (static_cast<size_t>(y) * w + x) * 3u;
rgb[idx + 0] = static_cast<uint8_t>((x * 3 + seed) & 0xFF);
rgb[idx + 1] = static_cast<uint8_t>((y * 5 + seed * 2) & 0xFF);
rgb[idx + 2] = static_cast<uint8_t>(((x + y) * 2 + seed * 3) & 0xFF);
}
}
std::string err;
return cz::encode_jpeg_rgb24(path, rgb.data(), w, h, 85, err);
}
std::string find_tool_path(const char* name) {
const char* path_env = std::getenv("PATH");
std::vector<std::string> dirs;
if (path_env && *path_env) {
std::string p(path_env);
size_t start = 0;
while (start <= p.size()) {
const size_t colon = p.find(':', start);
const std::string d =
(colon == std::string::npos) ? p.substr(start) : p.substr(start, colon - start);
if (!d.empty()) dirs.push_back(d);
if (colon == std::string::npos) break;
start = colon + 1;
}
}
dirs.push_back("/usr/local/bin");
dirs.push_back("/opt/homebrew/bin");
dirs.push_back("/usr/bin");
dirs.push_back("/bin");
for (const auto& d : dirs) {
const std::string cand = d + "/" + name;
if (::access(cand.c_str(), X_OK) == 0) {
return cand;
}
}
return name;
}
bool run_ffmpeg_sync(const std::vector<std::string>& args) {
const std::string exe = find_tool_path("ffmpeg");
std::vector<std::string> full_args;
full_args.push_back(exe);
full_args.insert(full_args.end(), args.begin(), args.end());
std::vector<char*> argv_ptrs;
argv_ptrs.reserve(full_args.size() + 1);
for (auto& a : full_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(exe.c_str(), argv_ptrs.data());
_exit(127);
}
int st = 0;
while (::waitpid(pid, &st, 0) < 0) {
if (errno != EINTR) return false;
}
return WIFEXITED(st) && WEXITSTATUS(st) == 0;
}
void test_backlight_dim_restore_and_raii() {
TempDir tmp("backlight");
const std::string bl_root = tmp.path + "/backlight";
const std::string lcd0 = bl_root + "/lcd0";
assert(cz::mkdir_p(lcd0));
const std::string brightness_path = lcd0 + "/brightness";
const std::string max_path = lcd0 + "/max_brightness";
write_text_file(brightness_path, "128\n");
write_text_file(max_path, "255\n");
// Dim, restore, and RAII restore on destruction
{
cz::BacklightController bl(bl_root);
assert(bl.has_hardware_backlight());
assert(!bl.is_dimmed());
assert(bl.dim());
assert(bl.is_dimmed());
assert(std::stoi(read_text_file(brightness_path)) == 0);
// Calling dim() again when already dimmed must NOT clobber saved "128"
assert(bl.dim());
assert(bl.is_dimmed());
assert(bl.restore());
assert(!bl.is_dimmed());
assert(std::stoi(read_text_file(brightness_path)) == 128);
// Dim again and let scope exit trigger ~BacklightController() -> restore()
assert(bl.dim());
assert(bl.is_dimmed());
assert(std::stoi(read_text_file(brightness_path)) == 0);
}
assert(std::stoi(read_text_file(brightness_path)) == 128);
// Missing directory safely sets has_hardware_backlight() == false and allows logical dim
{
cz::BacklightController missing_bl(tmp.path + "/nonexistent_backlight");
assert(!missing_bl.has_hardware_backlight());
assert(!missing_bl.is_dimmed());
missing_bl.dim();
assert(missing_bl.is_dimmed());
missing_bl.restore();
assert(!missing_bl.is_dimmed());
}
// Read-only brightness file safely sets has_hardware_backlight() == false (if not root)
if (::geteuid() != 0) {
const std::string ro_root = tmp.path + "/ro_backlight";
const std::string ro_lcd = ro_root + "/lcd0";
assert(cz::mkdir_p(ro_lcd));
const std::string ro_b = ro_lcd + "/brightness";
write_text_file(ro_b, "200");
assert(::chmod(ro_b.c_str(), 0444) == 0);
cz::BacklightController ro_bl(ro_root);
assert(!ro_bl.has_hardware_backlight());
ro_bl.dim();
assert(ro_bl.is_dimmed());
ro_bl.restore();
assert(!ro_bl.is_dimmed());
assert(read_text_file(ro_b) == "200");
::chmod(ro_b.c_str(), 0644);
}
}
void test_timelapse_photos_mode_and_caps() {
TempDir tmp("tl_photos");
const std::string out_dir = tmp.path + "/out";
assert(cz::mkdir_p(out_dir));
cz::SimCameraBackend backend;
cz::CameraStreamSpec spec;
spec.mode = "timelapse";
spec.main_width = 1640;
spec.main_height = 1232;
spec.preview_width = 226;
spec.preview_height = 170;
spec.fps = 30;
std::string err;
assert(backend.start(spec, err));
cz::AppConfig cfg;
cfg.output_dir = out_dir;
cfg.timelapse_resolution = "2mp";
cfg.timelapse_interval_sec = 1;
cfg.timelapse_output_mode = "photos";
cfg.timelapse_stop_mode = "shots";
cfg.timelapse_stop_value = 3;
cz::TimelapseEngine engine(&backend);
uint64_t now_ms = 10000;
assert(engine.start(cfg, now_ms));
assert(engine.state().running);
// Advance virtual clock across 3 intervals
for (int i = 0; i < 6 && engine.state().running; ++i) {
engine.tick(now_ms, cfg);
now_ms += 500;
}
const cz::TimelapseState st = engine.state();
assert(!st.running);
assert(!st.compiling);
assert(st.shots_taken == 3);
assert(st.last_error.empty());
assert(!st.result_path.empty());
assert(fs::is_directory(st.result_path));
assert(fs::path(st.result_path).filename().string().rfind("TL_", 0) == 0);
// Verify frame_0001.jpg .. frame_0003.jpg exist and no .tmp or .tl_work_* remain
for (int i = 1; i <= 3; ++i) {
char buf[32];
std::snprintf(buf, sizeof(buf), "frame_%04d.jpg", i);
const std::string frame_path = st.result_path + "/" + buf;
assert(fs::exists(frame_path));
assert(fs::file_size(frame_path) > 0);
cz::RgbImage img;
assert(cz::decode_jpeg_rgb24(frame_path, img, err));
assert(img.width == 1640 && img.height == 1232);
}
for (const auto& entry : fs::directory_iterator(st.result_path)) {
const std::string name = entry.path().filename().string();
assert(!name.empty() && name[0] != '.');
assert(name.find(".tmp") == std::string::npos);
}
assert(cz::scan_orphaned_timelapses(out_dir).empty());
// Also test duration cap
cz::AppConfig dur_cfg = cfg;
dur_cfg.timelapse_stop_mode = "duration";
dur_cfg.timelapse_stop_value = 2; // 2 seconds
dur_cfg.timelapse_interval_sec = 1;
uint64_t dur_ms = 50000;
assert(engine.start(dur_cfg, dur_ms));
for (int i = 0; i < 10 && engine.state().running; ++i) {
engine.tick(dur_ms, dur_cfg);
dur_ms += 500;
}
assert(!engine.state().running);
assert(engine.state().shots_taken >= 2);
assert(engine.state().elapsed_sec >= 2);
backend.stop();
}
void test_timelapse_compile_8mp_scaling_and_h264_fallback() {
TempDir tmp("tl_compile");
const std::string out_dir = tmp.path + "/out";
assert(cz::mkdir_p(out_dir));
const cz::TimelapseSessionPaths paths =
cz::create_timelapse_session(out_dir, true);
// Command builder verification: 8mp scales to 1440:1080; 2mp and 1080p omit scale
auto has_arg_pair = [](const std::vector<std::string>& args,
const std::string& key,
const std::string& val) {
for (size_t i = 0; i + 1 < args.size(); ++i) {
if (args[i] == key && args[i + 1] == val) return true;
}
return false;
};
auto has_arg = [](const std::vector<std::string>& args, const std::string& flag) {
return std::find(args.begin(), args.end(), flag) != args.end();
};
const auto cmd_8mp_hw =
cz::TimelapseEngine::build_compile_command(paths, 24, "8mp", true);
assert(has_arg_pair(cmd_8mp_hw, "-vf", "scale=1440:1080:flags=lanczos"));
assert(has_arg_pair(cmd_8mp_hw, "-c:v", "h264_v4l2m2m"));
assert(has_arg_pair(cmd_8mp_hw, "-f", "mp4"));
assert(has_arg_pair(cmd_8mp_hw, "-movflags", "+faststart"));
assert(has_arg(cmd_8mp_hw, paths.mp4_tmp_path));
const auto cmd_2mp_sw =
cz::TimelapseEngine::build_compile_command(paths, 24, "2mp", false);
assert(!has_arg(cmd_2mp_sw, "-vf"));
assert(has_arg_pair(cmd_2mp_sw, "-c:v", "libx264"));
assert(has_arg_pair(cmd_2mp_sw, "-preset", "veryfast"));
assert(has_arg_pair(cmd_2mp_sw, "-crf", "22"));
assert(has_arg_pair(cmd_2mp_sw, "-f", "mp4"));
const auto cmd_1080_hw =
cz::TimelapseEngine::build_compile_command(paths, 30, "1080p", true);
assert(!has_arg(cmd_1080_hw, "-vf"));
assert(has_arg_pair(cmd_1080_hw, "-framerate", "30"));
// Generate 3 real JPEGs and compile with 8mp scaling (triggers h264_v4l2m2m -> libx264 fallback on macOS)
for (int i = 1; i <= 3; ++i) {
const cz::StagedPaths fp = cz::next_timelapse_frame_paths(paths.work_dir, i);
assert(create_sample_jpeg(fp.final_path, 320, 240, static_cast<uint8_t>(i * 20)));
}
cz::TimelapseManifest m;
m.session_id = paths.session_id;
m.work_dir = paths.work_dir;
m.resolution = "8mp";
m.interval_sec = 5;
m.fps = 24;
m.frame_count = 3;
m.status = "recording";
assert(cz::write_timelapse_manifest(paths.manifest_path, m));
cz::TimelapseEngine engine;
int progress_calls = 0;
int last_cur = 0;
int last_tot = 0;
assert(engine.compile_session(
paths, 24, "8mp", [&](int cur, int total) {
++progress_calls;
last_cur = cur;
last_tot = total;
}));
assert(progress_calls > 0);
assert(last_tot == 3);
assert(last_cur >= 1 && last_cur <= 3);
assert(!fs::exists(paths.work_dir));
assert(!fs::exists(paths.mp4_tmp_path));
assert(fs::exists(paths.mp4_final_path));
assert(fs::file_size(paths.mp4_final_path) > 0);
assert(engine.state().result_path == paths.mp4_final_path);
assert(!engine.state().compiling);
assert(engine.state().last_error.empty());
// Probe compiled MP4 via GalleryStore to verify 1440x1080 scaled output
cz::GalleryStore gallery;
assert(gallery.refresh(out_dir));
assert(gallery.items().size() == 1);
cz::GalleryItem item = gallery.items()[0];
assert(item.type == cz::GalleryItemType::Video);
assert(gallery.probe_video_meta(item));
assert(item.width == 1440);
assert(item.height == 1080);
// Also test video-mode live capture + request_stop() + cancel_compile() preserving staging files
cz::SimCameraBackend sim;
cz::CameraStreamSpec spec;
spec.mode = "timelapse";
spec.main_width = 1640;
spec.main_height = 1232;
spec.preview_width = 226;
spec.preview_height = 170;
std::string err;
assert(sim.start(spec, err));
engine.set_backend(&sim);
cz::AppConfig vcfg;
vcfg.output_dir = out_dir;
vcfg.timelapse_resolution = "2mp";
vcfg.timelapse_interval_sec = 1;
vcfg.timelapse_output_mode = "video";
vcfg.timelapse_fps = 24;
vcfg.timelapse_stop_mode = "manual";
assert(engine.start(vcfg, 1000));
engine.tick(1000, vcfg);
engine.tick(2000, vcfg);
assert(engine.state().shots_taken == 2);
engine.request_stop();
assert(!engine.state().running);
assert(engine.state().needs_compile);
const cz::TimelapseSessionPaths vpaths = engine.session_paths();
assert(fs::is_directory(vpaths.work_dir));
sim.stop();
// Cancel during compile preserves staging work_dir and leaves no .part or final .mp4
const cz::TimelapseSessionPaths cancel_paths =
cz::create_timelapse_session(out_dir, true);
for (int i = 1; i <= 60; ++i) {
const cz::StagedPaths fp = cz::next_timelapse_frame_paths(cancel_paths.work_dir, i);
assert(create_sample_jpeg(fp.final_path, 640, 480, static_cast<uint8_t>(i)));
}
std::atomic<bool> cancel_triggered{false};
bool compile_ok = true;
std::thread compiler([&]() {
compile_ok = engine.compile_session(
cancel_paths, 24, "8mp", [&](int cur, int /*tot*/) {
if (cur >= 1 && !cancel_triggered.exchange(true)) {
engine.cancel_compile();
}
});
});
const auto cancel_dl =
std::chrono::steady_clock::now() + std::chrono::seconds(4);
while (!cancel_triggered.load() &&
std::chrono::steady_clock::now() < cancel_dl) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
if (!cancel_triggered.load()) {
engine.cancel_compile();
}
compiler.join();
assert(!compile_ok);
assert(!engine.state().compiling);
assert(!engine.state().last_error.empty());
assert(!fs::exists(cancel_paths.mp4_tmp_path));
assert(!fs::exists(cancel_paths.mp4_final_path));
assert(fs::is_directory(cancel_paths.work_dir));
assert(fs::exists(cancel_paths.work_dir + "/frame_0001.jpg"));
}
void test_timelapse_orphan_recovery_actions() {
TempDir tmp("tl_recover");
const std::string out_dir = tmp.path + "/out";
assert(cz::mkdir_p(out_dir));
auto make_orphan = [&](const std::string& suffix, int frames) {
const std::string work = out_dir + "/.tl_work_" + suffix;
assert(cz::mkdir_p(work));
for (int i = 1; i <= frames; ++i) {
const cz::StagedPaths fp = cz::next_timelapse_frame_paths(work, i);
assert(create_sample_jpeg(fp.final_path, 320, 240, static_cast<uint8_t>(i * 10)));
}
// Leave a hidden temp file to ensure recovery ignores/cleans it
write_text_file(work + "/.frame_0099.jpg.tmp", "partial");
cz::TimelapseManifest m;
m.session_id = suffix;
m.work_dir = work;
m.created_at = "2026-11-19T12:00:00Z";
m.resolution = "2mp";
m.interval_sec = 5;
m.fps = 24;
m.frame_count = frames;
m.status = "recording";
assert(cz::write_timelapse_manifest(work, m));
};
make_orphan("20261119_100001", 2);
make_orphan("20261119_100002", 2);
make_orphan("20261119_100003", 3);
const auto orphans = cz::scan_orphaned_timelapses(out_dir);
assert(orphans.size() == 3);
cz::TimelapseEngine engine;
std::string msg;
// 1. KeepPhotos moves frames to TL_<ts>/ cleanly and removes .tl_work_*
assert(engine.recover_session(orphans[0], cz::RecoveryAction::KeepPhotos, msg));
assert(!msg.empty());
assert(!fs::exists(orphans[0].work_dir));
const std::string kept_dir = out_dir + "/TL_" + orphans[0].session_id;
assert(fs::is_directory(kept_dir));
assert(fs::exists(kept_dir + "/frame_0001.jpg"));
assert(fs::exists(kept_dir + "/frame_0002.jpg"));
assert(!fs::exists(kept_dir + "/session.json"));
assert(!fs::exists(kept_dir + "/.frame_0099.jpg.tmp"));
// 2. Discard deletes .tl_work_* cleanly
assert(engine.recover_session(orphans[1], cz::RecoveryAction::Discard, msg));
assert(!msg.empty());
assert(!fs::exists(orphans[1].work_dir));
assert(!fs::exists(out_dir + "/TL_" + orphans[1].session_id));
assert(!fs::exists(out_dir + "/TL_" + orphans[1].session_id + ".mp4"));
// 3. Compile compiles to TL_<ts>.mp4 and deletes .tl_work_*
assert(engine.recover_session(orphans[2], cz::RecoveryAction::Compile, msg));
assert(!msg.empty());
assert(!fs::exists(orphans[2].work_dir));
const std::string compiled_mp4 = out_dir + "/TL_" + orphans[2].session_id + ".mp4";
assert(fs::exists(compiled_mp4));
assert(fs::file_size(compiled_mp4) > 0);
assert(cz::scan_orphaned_timelapses(out_dir).empty());
}
void test_gallery_scan_ignores_hidden_and_deletes_safely() {
TempDir tmp("gallery");
const std::string out_dir = tmp.path + "/out";
assert(cz::mkdir_p(out_dir));
// Create visible entries + hidden entries
const std::string img_path = out_dir + "/IMG_1.jpg";
assert(create_sample_jpeg(img_path, 640, 480, 11));
const std::string vid_path = out_dir + "/VID_1.mp4";
assert(run_ffmpeg_sync({"-y", "-f", "lavfi", "-i",
"testsrc=duration=1:size=320x240:rate=15",
"-c:v", "libx264", "-pix_fmt", "yuv420p", vid_path}));
const std::string tl_dir = out_dir + "/TL_20261119_1200";
assert(cz::mkdir_p(tl_dir));
assert(create_sample_jpeg(tl_dir + "/frame_0001.jpg", 640, 480, 33));
assert(create_sample_jpeg(tl_dir + "/frame_0002.jpg", 640, 480, 44));
// Hidden staging files/dirs that MUST be ignored
write_text_file(out_dir + "/.IMG_2.jpg.tmp", "hidden_jpg");
write_text_file(out_dir + "/.VID_2.mp4.part", "hidden_mp4");
assert(cz::mkdir_p(out_dir + "/.tl_work_20261119_1100"));
assert(create_sample_jpeg(out_dir + "/.tl_work_20261119_1100/frame_0001.jpg",
320, 240, 55));
// Set deterministic mtimes so newest-first order is strictly:
// 0: TL_20261119_1200 (newest)
// 1: VID_1.mp4 (middle)
// 2: IMG_1.jpg (oldest)
const auto now = fs::file_time_type::clock::now();
fs::last_write_time(img_path, now - std::chrono::seconds(30));
fs::last_write_time(vid_path, now - std::chrono::seconds(15));
fs::last_write_time(tl_dir, now - std::chrono::seconds(5));
cz::GalleryStore store;
assert(store.refresh(out_dir));
assert(!store.in_session());
assert(store.items().size() == 3);
assert(store.items()[0].filename == "TL_20261119_1200");
assert(store.items()[0].type == cz::GalleryItemType::TimelapseFolder);
assert(store.items()[0].photo_count == 2);
assert(store.items()[1].filename == "VID_1.mp4");
assert(store.items()[1].type == cz::GalleryItemType::Video);
assert(store.items()[2].filename == "IMG_1.jpg");
assert(store.items()[2].type == cz::GalleryItemType::Photo);
// Probe video metadata
cz::GalleryItem vid_meta = store.items()[1];
assert(store.probe_video_meta(vid_meta));
assert(vid_meta.width == 320 && vid_meta.height == 240);
assert(vid_meta.duration_sec > 0.5);
// Load previews for Photo, Video poster, and TimelapseFolder
std::string err;
cz::RgbImage preview;
assert(store.load_preview_rgb24(2, 320, 128, preview, err));
assert(preview.width > 0 && preview.width <= 320);
assert(preview.height > 0 && preview.height <= 128);
assert(preview.rgb24.size() ==
static_cast<size_t>(preview.width) * preview.height * 3u);
assert(store.load_preview_rgb24(1, 320, 128, preview, err));
assert(preview.width > 0 && preview.width <= 320);
assert(preview.height > 0 && preview.height <= 128);
assert(store.load_preview_rgb24(0, 320, 128, preview, err));
assert(preview.width > 0 && preview.width <= 320);
assert(preview.height > 0 && preview.height <= 128);
// Enter and exit TL session
assert(store.enter_session(0));
assert(store.in_session());
assert(store.session_name() == "TL_20261119_1200");
assert(store.items().size() == 2);
assert(store.items()[0].filename == "frame_0001.jpg");
assert(store.items()[1].filename == "frame_0002.jpg");
// Delete single photo inside session
assert(store.delete_item(0, err));
assert(store.items().size() == 1);
assert(!fs::exists(tl_dir + "/frame_0001.jpg"));
assert(fs::exists(tl_dir + "/frame_0002.jpg"));
// Exit session back to root
assert(store.exit_session());
assert(!store.in_session());
assert(store.items().size() == 3);
assert(store.items()[0].photo_count == 1);
// Delete TL folder, Video, and Photo from root
assert(store.delete_item(0, err));
assert(!fs::exists(tl_dir));
assert(store.items().size() == 2);
assert(store.delete_item(0, err));
assert(!fs::exists(vid_path));
assert(store.items().size() == 1);
assert(store.delete_item(0, err));
assert(!fs::exists(img_path));
assert(store.items().empty());
// Out-of-bounds and missing directory safety
assert(!store.enter_session(0));
assert(!store.exit_session());
assert(!store.delete_item(-1, err));
assert(!store.load_preview_rgb24(0, 320, 128, preview, err));
assert(!store.refresh(tmp.path + "/does_not_exist"));
}
void test_video_player_decodes_frames_seeks_and_handles_silent_mp4() {
TempDir tmp("vplayer");
const std::string mp4_path = tmp.path + "/silent_test.mp4";
assert(run_ffmpeg_sync({"-y", "-f", "lavfi", "-i",
"testsrc=duration=2:size=320x240:rate=15",
"-c:v", "libx264", "-pix_fmt", "yuv420p", mp4_path}));
cz::VideoPlayer player;
assert(player.open(mp4_path, 226, 128));
const cz::VideoPlayerState opened = player.state();
assert(opened.stopped);
assert(!opened.playing);
assert(!opened.paused);
assert(opened.duration_sec > 1.5);
assert(opened.width > 0 && opened.width <= 226);
assert(opened.height > 0 && opened.height <= 128);
assert(opened.error.empty());
// play(true) MUST succeed cleanly on a silent MP4 lacking an audio stream
assert(player.play(true));
assert(player.state().playing);
assert(!player.state().paused);
assert(player.state().error.empty());
cz::PreviewFrame f1;
bool got_f1 = false;
const auto dl1 = std::chrono::steady_clock::now() + std::chrono::seconds(4);
while (std::chrono::steady_clock::now() < dl1) {
if (player.poll_frame(f1)) {
got_f1 = true;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(15));
}
assert(got_f1);
assert(f1.width > 0 && f1.width <= 226);
assert(f1.height > 0 && f1.height <= 128);
assert(f1.rgb24.size() ==
static_cast<size_t>(f1.width) * static_cast<size_t>(f1.height) * 3u);
// Seek forward +1.0s and receive a newer frame
assert(player.seek_delta(1.0));
cz::PreviewFrame f_seek;
bool got_seek = false;
const auto dl2 = std::chrono::steady_clock::now() + std::chrono::seconds(4);
while (std::chrono::steady_clock::now() < dl2) {
if (player.poll_frame(f_seek)) {
got_seek = true;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(15));
}
assert(got_seek);
assert(f_seek.seq > f1.seq);
assert(player.state().position_sec >= 0.9);
player.toggle_mute();
assert(player.state().muted);
player.toggle_mute();
assert(!player.state().muted);
player.pause();
assert(player.state().paused);
assert(!player.state().playing);
player.stop();
assert(player.state().stopped);
assert(!player.state().playing);
assert(!player.state().paused);
// Also test MP4 with audio + pcm_sink callback
const std::string audio_mp4 = tmp.path + "/audio_test.mp4";
assert(run_ffmpeg_sync({"-y", "-f", "lavfi", "-i",
"testsrc=duration=1:size=320x240:rate=15",
"-f", "lavfi", "-i",
"sine=frequency=440:sample_rate=44100:duration=1",
"-shortest", "-c:v", "libx264", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "64k", audio_mp4}));
std::atomic<size_t> pcm_samples{0};
player.set_pcm_sink([&](const int16_t* data, size_t count) {
if (data && count > 0) {
pcm_samples.fetch_add(count);
}
});
assert(player.open(audio_mp4, 226, 128));
assert(player.play(true));
cz::PreviewFrame af;
const auto dl3 = std::chrono::steady_clock::now() + std::chrono::seconds(4);
while (std::chrono::steady_clock::now() < dl3) {
player.poll_frame(af);
if (af.seq > 0 && pcm_samples.load() > 0) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
// Muted play(false) on audio MP4 skips pcm_sink and reaches EOF naturally
pcm_samples.store(0);
assert(player.open(audio_mp4, 226, 128));
assert(player.state().has_audio);
assert(player.play(false));
assert(player.state().muted);
assert(player.seek_delta(-10.0));
assert(player.state().position_sec >= 0.0 && player.state().position_sec < 0.1);
const auto dl4 = std::chrono::steady_clock::now() + std::chrono::seconds(4);
while (!player.state().eof && std::chrono::steady_clock::now() < dl4) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
assert(player.state().eof);
assert(player.state().stopped);
assert(pcm_samples.load() == 0);
player.stop();
// Missing video file fails cleanly
assert(!player.open(tmp.path + "/nonexistent.mp4", 226, 128));
assert(!player.state().error.empty());
}
} // namespace
int main() {
test_backlight_dim_restore_and_raii();
test_timelapse_photos_mode_and_caps();
test_timelapse_compile_8mp_scaling_and_h264_fallback();
test_timelapse_orphan_recovery_actions();
test_gallery_scan_ignores_hidden_and_deletes_safely();
test_video_player_decodes_frames_seeks_and_handles_silent_mp4();
std::cout << "All test_timelapse_and_gallery tests passed!\n";
return 0;
}