diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index ad1c5a3..398092b 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -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() diff --git a/app/src/backlight.cpp b/app/src/backlight.cpp new file mode 100644 index 0000000..e4b9911 --- /dev/null +++ b/app/src/backlight.cpp @@ -0,0 +1,212 @@ +#include "backlight.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(s[start]))) { + ++start; + } + size_t end = s.size(); + while (end > start && + std::isspace(static_cast(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 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 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(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(w); + continue; + } + if (w < 0 && errno == EINTR) { + continue; + } + ::close(fd); + return false; + } + ::close(fd); + return true; +} + +bool BacklightController::dim() { + std::lock_guard 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 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 lock(mutex_); + return dimmed_; +} + +bool BacklightController::has_hardware_backlight() const { + std::lock_guard lock(mutex_); + return has_hardware_backlight_; +} + +} // namespace cz diff --git a/app/src/backlight.hpp b/app/src/backlight.hpp new file mode 100644 index 0000000..7ff60b5 --- /dev/null +++ b/app/src/backlight.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include +#include + +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 diff --git a/app/src/gallery_model.cpp b/app/src/gallery_model.cpp new file mode 100644 index 0000000..e6ad5e9 --- /dev/null +++ b/app/src/gallery_model.cpp @@ -0,0 +1,542 @@ +#include "gallery_model.hpp" + +#include "config.hpp" +#include "video_player.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(st.st_mtimespec.tv_sec); + nsec = static_cast(st.st_mtimespec.tv_nsec); +#else + sec = static_cast(st.st_mtim.tv_sec); + nsec = static_cast(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(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(cinfo.image_width); + out_h = static_cast(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 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(target_w) * static_cast(target_h) * 3u; + std::vector 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(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(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 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 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(std::max(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(std::max(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 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(std::max(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(items_.size())) { + return false; + } + const GalleryItem& target = items_[static_cast(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& 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(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(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(items_.size())) { + out_err = "gallery index out of range"; + return false; + } + const GalleryItem target = items_[static_cast(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 diff --git a/app/src/gallery_model.hpp b/app/src/gallery_model.hpp new file mode 100644 index 0000000..af3f248 --- /dev/null +++ b/app/src/gallery_model.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include "jpeg_pipeline.hpp" + +#include +#include +#include + +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& 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 items_; +}; + +} // namespace cz diff --git a/app/src/timelapse_engine.cpp b/app/src/timelapse_engine.cpp new file mode 100644 index 0000000..504df52 --- /dev/null +++ b/app/src/timelapse_engine.cpp @@ -0,0 +1,967 @@ +#include "timelapse_engine.hpp" + +#include "video_player.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace cz { + +namespace { + +std::string to_lower_ascii(std::string s) { + for (char& c : s) { + c = static_cast(std::tolower(static_cast(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 lock(mutex_); + state_.running = false; +} + +void TimelapseEngine::set_backend(ICameraBackend* backend) { + std::lock_guard lock(mutex_); + backend_ = backend; +} + +std::vector 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 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 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 lock(mutex_); + if (!state_.running || capturing_) { + return; + } + clamped_now = std::max(now_ms, start_ms_); + state_.elapsed_sec = static_cast((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((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 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(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((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 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& on_progress, + std::string& out_err) { + out_err.clear(); + + std::vector 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 argv_ptrs; + argv_ptrs.reserve(args.size() + 1); + for (auto& a : args) { + argv_ptrs.push_back(const_cast(a.c_str())); + } + argv_ptrs.push_back(nullptr); + + { + std::lock_guard 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 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 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 lock(mutex_); + state_.compile_current = cur; + state_.compile_total = total_frames; + state_.compile_progress = + total_frames > 0 + ? static_cast(cur) / static_cast(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 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(nfds); + pfds[nfds++] = {out_pipe[0], POLLIN, 0}; + } + if (err_open) { + err_idx = static_cast(nfds); + pfds[nfds++] = {err_pipe[0], POLLIN, 0}; + } + wake_idx = static_cast(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(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(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 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 on_progress) { + std::lock_guard compile_guard(compile_mutex_); + const int total_frames = count_valid_jpegs(paths.work_dir); + if (total_frames <= 0) { + std::lock_guard 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 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 lock(mutex_); + state_.compiling = false; + state_.last_error = "ffmpeg executable not found"; + return false; + } + + { + std::lock_guard 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 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 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 plock(compile_proc_mutex_); + cancelled = cancel_compile_requested_; + } + + if (!ok || cancelled) { + remove_silent(paths.mp4_tmp_path); + std::lock_guard 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 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 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 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 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 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 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 lock(mutex_); + return state_; +} + +TimelapseSessionPaths TimelapseEngine::session_paths() const { + std::lock_guard lock(mutex_); + return session_; +} + +} // namespace cz diff --git a/app/src/timelapse_engine.hpp b/app/src/timelapse_engine.hpp new file mode 100644 index 0000000..9f2f4ca --- /dev/null +++ b/app/src/timelapse_engine.hpp @@ -0,0 +1,106 @@ +#pragma once + +#include "camera_backend.hpp" +#include "config.hpp" +#include "storage.hpp" + +#include +#include +#include +#include +#include +#include + +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 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 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& 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 diff --git a/app/src/video_player.cpp b/app/src/video_player.cpp new file mode 100644 index 0000000..0cb02b4 --- /dev/null +++ b/app/src/video_player.cpp @@ -0,0 +1,1372 @@ +#include "video_player.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cz { + +namespace media_detail { + +namespace { + +bool is_executable_regular_file(const std::string& path) { + struct stat st {}; + if (::stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) { + return false; + } + return ::access(path.c_str(), X_OK) == 0; +} + +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; + } +} + +bool create_wake_pipe(int& out_r, int& out_w) { + int fds[2] = {-1, -1}; + if (::pipe(fds) != 0) { + return false; + } + set_cloexec(fds[0]); + set_cloexec(fds[1]); + set_nonblocking(fds[0]); + set_nonblocking(fds[1]); + out_r = fds[0]; + out_w = fds[1]; + return true; +} + +void signal_wake_pipe(int fd) { + if (fd >= 0) { + const uint8_t byte = 1; + const ssize_t ignored = ::write(fd, &byte, 1); + (void)ignored; + } +} + +std::string format_seconds_c_locale(double sec) { + std::ostringstream oss; + oss.imbue(std::locale::classic()); + oss.setf(std::ios::fixed); + oss.precision(3); + oss << std::max(0.0, sec); + return oss.str(); +} + +double parse_rate_fraction(const std::string& s) { + if (s.empty() || s == "N/A") { + return 0.0; + } + const size_t slash = s.find('/'); + if (slash == std::string::npos) { + const double val = std::strtod(s.c_str(), nullptr); + return std::isfinite(val) && val > 0.0 ? val : 0.0; + } + const double num = std::strtod(s.substr(0, slash).c_str(), nullptr); + const double den = std::strtod(s.substr(slash + 1).c_str(), nullptr); + if (!std::isfinite(num) || !std::isfinite(den) || den <= 0.0 || num <= 0.0) { + return 0.0; + } + return num / den; +} + +double parse_double_safe(const std::string& s) { + if (s.empty() || s == "N/A") { + return 0.0; + } + char* end = nullptr; + const double v = std::strtod(s.c_str(), &end); + if (end == s.c_str() || !std::isfinite(v) || v < 0.0) { + return 0.0; + } + return v; +} + +std::string trim_cr_ws(std::string s) { + while (!s.empty() && + (s.back() == '\r' || s.back() == '\n' || + std::isspace(static_cast(s.back())))) { + s.pop_back(); + } + return s; +} + +} // namespace + +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(s[off + i])) != + std::tolower(static_cast(suffix[i]))) { + return false; + } + } + return true; +} + +bool spawn_stdout_process(const std::string& exe, + const std::vector& args, + pid_t& out_pid, + int& out_stdout_fd) { + out_pid = -1; + out_stdout_fd = -1; + + int out_pipe[2] = {-1, -1}; + if (::pipe(out_pipe) != 0) { + return false; + } + + std::vector argv_ptrs; + argv_ptrs.reserve(args.size() + 1); + for (const auto& a : args) { + argv_ptrs.push_back(const_cast(a.c_str())); + } + argv_ptrs.push_back(nullptr); + + const pid_t pid = ::fork(); + if (pid < 0) { + ::close(out_pipe[0]); + ::close(out_pipe[1]); + return false; + } + if (pid == 0) { + ::close(out_pipe[0]); + if (::dup2(out_pipe[1], STDOUT_FILENO) < 0) { + _exit(127); + } + if (out_pipe[1] > 2) { + ::close(out_pipe[1]); + } + const int devnull = ::open("/dev/null", O_RDWR); + if (devnull >= 0) { + ::dup2(devnull, STDIN_FILENO); + ::dup2(devnull, STDERR_FILENO); + if (devnull > 2) { + ::close(devnull); + } + } + ::execvp(exe.c_str(), argv_ptrs.data()); + _exit(127); + } + + ::close(out_pipe[1]); + set_cloexec(out_pipe[0]); + set_nonblocking(out_pipe[0]); + out_pid = pid; + out_stdout_fd = out_pipe[0]; + return true; +} + +void ignore_sigpipe_once() { + static std::once_flag flag; + std::call_once(flag, []() { std::signal(SIGPIPE, SIG_IGN); }); +} + +std::string resolve_executable(const std::string& name) { + if (name.empty()) { + return ""; + } + if (name.find('/') != std::string::npos) { + return is_executable_regular_file(name) ? name : ""; + } + + const char* path_env = std::getenv("PATH"); + if (path_env && *path_env) { + std::string path_str(path_env); + size_t start = 0; + while (start <= path_str.size()) { + const size_t colon = path_str.find(':', start); + const std::string dir = (colon == std::string::npos) + ? path_str.substr(start) + : path_str.substr(start, colon - start); + if (!dir.empty()) { + const std::string cand = + (dir.back() == '/') ? (dir + name) : (dir + "/" + name); + if (is_executable_regular_file(cand)) { + return cand; + } + } + if (colon == std::string::npos) { + break; + } + start = colon + 1; + } + } + + static constexpr const char* kFallbackDirs[] = { + "/usr/local/bin", + "/opt/homebrew/bin", + "/usr/bin", + "/bin", + }; + for (const char* dir : kFallbackDirs) { + const std::string cand = std::string(dir) + "/" + name; + if (is_executable_regular_file(cand)) { + return cand; + } + } + return ""; +} + +bool reap_pid_timeout(pid_t pid, int timeout_ms, int* out_status) { + if (pid <= 0) { + return true; + } + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + while (true) { + int st = 0; + const pid_t wr = ::waitpid(pid, &st, WNOHANG); + if (wr == pid) { + if (out_status) *out_status = st; + return true; + } + if (wr < 0) { + if (errno == EINTR) { + continue; + } + return errno == ECHILD; + } + if (std::chrono::steady_clock::now() >= deadline) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } +} + +void kill_and_reap(pid_t& pid) { + if (pid <= 0) { + pid = -1; + return; + } + const pid_t target = pid; + pid = -1; + ::kill(target, SIGTERM); + if (!reap_pid_timeout(target, 400, nullptr)) { + ::kill(target, SIGKILL); + int st = 0; + while (::waitpid(target, &st, 0) < 0 && errno == EINTR) { + } + } +} + +bool read_exact_with_wake(int fd, + int wake_fd, + uint8_t* dst, + size_t n, + bool& out_woken, + bool& out_eof) { + out_woken = false; + out_eof = false; + size_t off = 0; + while (off < n) { + pollfd pfds[2] = { + {fd, POLLIN, 0}, + {wake_fd, POLLIN, 0}, + }; + const int nfds = (wake_fd >= 0) ? 2 : 1; + const int rc = ::poll(pfds, static_cast(nfds), -1); + if (rc < 0) { + if (errno == EINTR) { + continue; + } + out_eof = true; + return false; + } + if (wake_fd >= 0 && (pfds[1].revents & (POLLIN | POLLHUP | POLLERR))) { + out_woken = true; + return false; + } + if (pfds[0].revents & (POLLIN | POLLHUP | POLLERR)) { + while (off < n) { + const ssize_t r = ::read(fd, dst + off, n - off); + if (r > 0) { + off += static_cast(r); + continue; + } + if (r == 0) { + out_eof = true; + return false; + } + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + break; + } + out_eof = true; + return false; + } + } + } + return true; +} + +VideoProbeResult probe_video_file(const std::string& path) { + VideoProbeResult res; + if (path.empty()) { + res.error = "empty video path"; + return res; + } + struct stat st {}; + if (::stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0) { + res.error = "video file missing or empty"; + return res; + } + + const std::string ffprobe = resolve_executable("ffprobe"); + if (ffprobe.empty()) { + res.error = "ffprobe executable not found"; + return res; + } + + ignore_sigpipe_once(); + + int out_pipe[2] = {-1, -1}; + int err_pipe[2] = {-1, -1}; + if (::pipe(out_pipe) != 0) { + res.error = "pipe failed"; + return res; + } + if (::pipe(err_pipe) != 0) { + ::close(out_pipe[0]); + ::close(out_pipe[1]); + res.error = "pipe failed"; + return res; + } + + std::vector args = { + ffprobe, + "-v", + "error", + "-show_entries", + "stream=codec_type,width,height,r_frame_rate,avg_frame_rate,duration", + "-show_entries", + "format=duration", + "-of", + "default", + path, + }; + std::vector argv_ptrs; + argv_ptrs.reserve(args.size() + 1); + for (auto& a : args) { + argv_ptrs.push_back(const_cast(a.c_str())); + } + argv_ptrs.push_back(nullptr); + + const pid_t pid = ::fork(); + if (pid < 0) { + ::close(out_pipe[0]); + ::close(out_pipe[1]); + ::close(err_pipe[0]); + ::close(err_pipe[1]); + res.error = "fork failed"; + return res; + } + if (pid == 0) { + ::close(out_pipe[0]); + ::close(err_pipe[0]); + ::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(ffprobe.c_str(), argv_ptrs.data()); + _exit(127); + } + + ::close(out_pipe[1]); + ::close(err_pipe[1]); + set_nonblocking(out_pipe[0]); + set_nonblocking(err_pipe[0]); + + std::string stdout_text; + std::string stderr_text; + bool out_open = true; + bool err_open = true; + const auto dl = std::chrono::steady_clock::now() + std::chrono::seconds(4); + + while ((out_open || err_open) && std::chrono::steady_clock::now() < dl) { + pollfd pfds[2]{}; + nfds_t nfds = 0; + int out_idx = -1; + int err_idx = -1; + if (out_open) { + out_idx = static_cast(nfds); + pfds[nfds++] = {out_pipe[0], POLLIN, 0}; + } + if (err_open) { + err_idx = static_cast(nfds); + pfds[nfds++] = {err_pipe[0], POLLIN, 0}; + } + const int rc = ::poll(pfds, nfds, 100); + if (rc < 0) { + if (errno == EINTR) continue; + break; + } + auto drain = [](int fd, std::string& dst, bool& open_flag) { + char buf[1024]; + while (true) { + const ssize_t r = ::read(fd, buf, sizeof(buf)); + if (r > 0) { + if (dst.size() < 65536) { + dst.append(buf, static_cast(r)); + } + continue; + } + if (r == 0) { + open_flag = false; + break; + } + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) break; + open_flag = false; + break; + } + }; + if (out_idx >= 0 && (pfds[out_idx].revents & (POLLIN | POLLHUP | POLLERR))) { + drain(out_pipe[0], stdout_text, out_open); + } + if (err_idx >= 0 && (pfds[err_idx].revents & (POLLIN | POLLHUP | POLLERR))) { + drain(err_pipe[0], stderr_text, err_open); + } + } + + ::close(out_pipe[0]); + ::close(err_pipe[0]); + + int status = 0; + if (!reap_pid_timeout(pid, 500, &status)) { + pid_t tmp_pid = pid; + kill_and_reap(tmp_pid); + res.error = "ffprobe timed out"; + return res; + } + + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + res.error = stderr_text.empty() ? "ffprobe failed" : trim_cr_ws(stderr_text); + return res; + } + + enum class Section { None, Stream, Format }; + Section sec = Section::None; + std::string codec_type; + int stream_w = 0; + int stream_h = 0; + double stream_avg_fps = 0.0; + double stream_r_fps = 0.0; + double stream_dur = 0.0; + double format_dur = 0.0; + double video_stream_dur = 0.0; + + auto flush_stream = [&]() { + if (codec_type == "video" && res.width == 0 && stream_w > 0 && stream_h > 0) { + res.width = stream_w; + res.height = stream_h; + const double f = stream_avg_fps > 0.0 ? stream_avg_fps : stream_r_fps; + if (f > 0.0) { + res.fps = std::clamp(f, 1.0, 120.0); + } + if (stream_dur > 0.0) { + video_stream_dur = stream_dur; + } + } else if (codec_type == "audio") { + res.has_audio = true; + } + codec_type.clear(); + stream_w = 0; + stream_h = 0; + stream_avg_fps = 0.0; + stream_r_fps = 0.0; + stream_dur = 0.0; + }; + + std::istringstream iss(stdout_text); + std::string line; + while (std::getline(iss, line)) { + line = trim_cr_ws(line); + if (line.empty()) continue; + if (line == "[STREAM]") { + sec = Section::Stream; + codec_type.clear(); + stream_w = 0; + stream_h = 0; + stream_avg_fps = 0.0; + stream_r_fps = 0.0; + stream_dur = 0.0; + continue; + } + if (line == "[/STREAM]") { + flush_stream(); + sec = Section::None; + continue; + } + if (line == "[FORMAT]") { + sec = Section::Format; + continue; + } + if (line == "[/FORMAT]") { + sec = Section::None; + continue; + } + const size_t eq = line.find('='); + if (eq == std::string::npos) continue; + const std::string key = line.substr(0, eq); + const std::string val = line.substr(eq + 1); + if (sec == Section::Stream) { + if (key == "codec_type") codec_type = val; + else if (key == "width") stream_w = std::atoi(val.c_str()); + else if (key == "height") stream_h = std::atoi(val.c_str()); + else if (key == "avg_frame_rate") stream_avg_fps = parse_rate_fraction(val); + else if (key == "r_frame_rate") stream_r_fps = parse_rate_fraction(val); + else if (key == "duration") stream_dur = parse_double_safe(val); + } else if (sec == Section::Format) { + if (key == "duration") format_dur = parse_double_safe(val); + } + } + + res.duration_sec = format_dur > 0.0 ? format_dur : video_stream_dur; + if (res.width <= 0 || res.height <= 0) { + res.error = "no valid video stream found"; + return res; + } + + res.ok = true; + res.error.clear(); + return res; +} + +bool compute_fit_dimensions(int src_w, + int src_h, + int max_w, + int max_h, + int& out_w, + int& out_h) { + out_w = 0; + out_h = 0; + if (src_w <= 0 || src_h <= 0 || max_w <= 1 || max_h <= 1) { + return false; + } + const double scale = + std::min(1.0, std::min(static_cast(max_w) / src_w, + static_cast(max_h) / src_h)); + int w = static_cast(std::floor(src_w * scale)) & ~1; + int h = static_cast(std::floor(src_h * scale)) & ~1; + w = std::clamp(w, 2, max_w & ~1); + h = std::clamp(h, 2, max_h & ~1); + out_w = w; + out_h = h; + return true; +} + +bool aspect_scale_rgb24(const uint8_t* src, + int src_w, + int src_h, + int max_w, + int max_h, + std::vector& out_rgb, + int& out_w, + int& out_h) { + out_rgb.clear(); + out_w = 0; + out_h = 0; + if (!src || src_w <= 0 || src_h <= 0 || max_w <= 0 || max_h <= 0) { + return false; + } + + if (src_w <= max_w && src_h <= max_h) { + out_w = src_w; + out_h = src_h; + const size_t total = static_cast(src_w) * src_h * 3u; + out_rgb.assign(src, src + total); + return true; + } + + const double scale = std::min(static_cast(max_w) / src_w, + static_cast(max_h) / src_h); + out_w = std::clamp(static_cast(std::floor(src_w * scale)), 1, max_w); + out_h = std::clamp(static_cast(std::floor(src_h * scale)), 1, max_h); + + out_rgb.resize(static_cast(out_w) * out_h * 3u); + for (int y = 0; y < out_h; ++y) { + const double sy = + (static_cast(y) + 0.5) * src_h / static_cast(out_h) - 0.5; + const int y0 = std::clamp(static_cast(std::floor(sy)), 0, src_h - 1); + const int y1 = std::min(y0 + 1, src_h - 1); + const double fy = std::clamp(sy - y0, 0.0, 1.0); + + for (int x = 0; x < out_w; ++x) { + const double sx = + (static_cast(x) + 0.5) * src_w / static_cast(out_w) - 0.5; + const int x0 = std::clamp(static_cast(std::floor(sx)), 0, src_w - 1); + const int x1 = std::min(x0 + 1, src_w - 1); + const double fx = std::clamp(sx - x0, 0.0, 1.0); + + const uint8_t* p00 = src + (static_cast(y0) * src_w + x0) * 3u; + const uint8_t* p10 = src + (static_cast(y0) * src_w + x1) * 3u; + const uint8_t* p01 = src + (static_cast(y1) * src_w + x0) * 3u; + const uint8_t* p11 = src + (static_cast(y1) * src_w + x1) * 3u; + + uint8_t* dst = out_rgb.data() + (static_cast(y) * out_w + x) * 3u; + for (int c = 0; c < 3; ++c) { + const double top = p00[c] * (1.0 - fx) + p10[c] * fx; + const double bot = p01[c] * (1.0 - fx) + p11[c] * fx; + const double v = top * (1.0 - fy) + bot * fy; + dst[c] = static_cast(std::clamp(std::lround(v), 0L, 255L)); + } + } + } + return true; +} + +} // namespace media_detail + +VideoPlayer::VideoPlayer() { media_detail::ignore_sigpipe_once(); } + +VideoPlayer::~VideoPlayer() { stop(); } + +void VideoPlayer::set_pcm_sink( + std::function sink) { + std::lock_guard lock(state_mutex_); + pcm_sink_ = std::move(sink); +} + +bool VideoPlayer::open(const std::string& mp4_path, int max_w, int max_h) { + std::lock_guard ctrl(control_mutex_); + stop_workers_locked_ctrl(); + + const media_detail::VideoProbeResult probe = + media_detail::probe_video_file(mp4_path); + int target_w = 0; + int target_h = 0; + const bool dims_ok = + probe.ok && media_detail::compute_fit_dimensions(probe.width, probe.height, + max_w, max_h, target_w, + target_h); + + { + std::lock_guard fr_lock(frame_mutex_); + latest_frame_ = PreviewFrame{}; + last_polled_seq_ = seq_counter_; + } + + std::lock_guard lock(state_mutex_); + if (!probe.ok || !dims_ok) { + opened_ = false; + mp4_path_.clear(); + state_ = VideoPlayerState{}; + state_.error = probe.error.empty() ? "invalid video dimensions" : probe.error; + return false; + } + + mp4_path_ = mp4_path; + max_w_ = max_w; + max_h_ = max_h; + fps_ = probe.fps; + opened_ = true; + + state_ = VideoPlayerState{}; + state_.stopped = true; + state_.playing = false; + state_.paused = false; + state_.muted = false; + state_.eof = false; + state_.position_sec = 0.0; + state_.duration_sec = probe.duration_sec; + state_.width = target_w; + state_.height = target_h; + state_.has_audio = probe.has_audio; + state_.error.clear(); + return true; +} + +bool VideoPlayer::play(bool enable_audio) { + std::lock_guard ctrl(control_mutex_); + + bool already_playing = false; + double start_pos = 0.0; + bool has_audio = false; + bool was_muted = false; + { + std::lock_guard lock(state_mutex_); + if (!opened_ || mp4_path_.empty()) { + state_.error = "no video opened"; + return false; + } + already_playing = state_.playing; + if (state_.eof) { + state_.position_sec = 0.0; + state_.eof = false; + } + start_pos = state_.position_sec; + has_audio = state_.has_audio; + was_muted = state_.muted; + state_.muted = !enable_audio; + } + + const bool want_audio = enable_audio && has_audio; + if (already_playing) { + if (was_muted != !enable_audio) { + if (want_audio) { + start_audio_worker_locked_ctrl(start_pos); + } else { + stop_audio_worker_locked_ctrl(); + } + } + return true; + } + + return start_playback_locked_ctrl(start_pos, want_audio); +} + +void VideoPlayer::pause() { + std::lock_guard ctrl(control_mutex_); + { + std::lock_guard lock(state_mutex_); + if (!opened_ || state_.stopped) { + return; + } + if (state_.paused && !state_.playing) { + return; + } + } + stop_workers_locked_ctrl(); + std::lock_guard lock(state_mutex_); + if (!state_.eof) { + state_.playing = false; + state_.paused = true; + state_.stopped = false; + } +} + +void VideoPlayer::toggle_mute() { + std::lock_guard ctrl(control_mutex_); + bool is_playing = false; + bool now_muted = false; + bool has_audio = false; + double pos = 0.0; + { + std::lock_guard lock(state_mutex_); + state_.muted = !state_.muted; + now_muted = state_.muted; + is_playing = state_.playing; + has_audio = state_.has_audio; + pos = state_.position_sec; + } + if (is_playing && has_audio) { + if (now_muted) { + stop_audio_worker_locked_ctrl(); + } else { + start_audio_worker_locked_ctrl(pos); + } + } +} + +bool VideoPlayer::seek_delta(double delta_sec) { + std::lock_guard ctrl(control_mutex_); + bool was_playing = false; + bool want_audio = false; + double new_pos = 0.0; + { + std::lock_guard lock(state_mutex_); + if (!opened_ || mp4_path_.empty()) { + return false; + } + was_playing = state_.playing; + want_audio = state_.has_audio && !state_.muted; + const double max_pos = state_.duration_sec > 0.1 + ? (state_.duration_sec - 0.05) + : state_.duration_sec; + new_pos = std::clamp(state_.position_sec + delta_sec, 0.0, + std::max(0.0, max_pos)); + } + + stop_workers_locked_ctrl(); + + { + std::lock_guard lock(state_mutex_); + state_.position_sec = new_pos; + state_.eof = false; + if (!was_playing && state_.stopped) { + state_.stopped = true; + state_.paused = false; + } + } + + if (was_playing) { + return start_playback_locked_ctrl(new_pos, want_audio); + } + return true; +} + +bool VideoPlayer::poll_frame(PreviewFrame& out_frame) { + std::lock_guard fr_lock(frame_mutex_); + if (latest_frame_.seq == 0 || latest_frame_.seq <= last_polled_seq_) { + return false; + } + out_frame = latest_frame_; + last_polled_seq_ = latest_frame_.seq; + return true; +} + +void VideoPlayer::stop() { + std::lock_guard ctrl(control_mutex_); + stop_workers_locked_ctrl(); + std::lock_guard lock(state_mutex_); + state_.playing = false; + state_.paused = false; + state_.stopped = true; + state_.eof = false; + state_.position_sec = 0.0; +} + +VideoPlayerState VideoPlayer::state() const { + std::lock_guard lock(state_mutex_); + return state_; +} + +bool VideoPlayer::start_playback_locked_ctrl(double start_pos_sec, + bool want_audio) { + stop_workers_locked_ctrl(); + + const std::string ffmpeg = media_detail::resolve_executable("ffmpeg"); + if (ffmpeg.empty()) { + std::lock_guard lock(state_mutex_); + state_.error = "ffmpeg executable not found"; + state_.playing = false; + state_.stopped = true; + return false; + } + + std::string path; + int w = 0; + int h = 0; + double fps = 24.0; + { + std::lock_guard lock(state_mutex_); + path = mp4_path_; + w = state_.width; + h = state_.height; + fps = fps_; + } + + if (!media_detail::create_wake_pipe(video_wake_r_, video_wake_w_)) { + std::lock_guard lock(state_mutex_); + state_.error = "failed to create wakeup pipe"; + return false; + } + + std::vector vargs = { + ffmpeg, + "-nostdin", + "-loglevel", + "error", + }; + if (start_pos_sec > 0.001) { + vargs.push_back("-ss"); + vargs.push_back(media_detail::format_seconds_c_locale(start_pos_sec)); + } + vargs.push_back("-i"); + vargs.push_back(path); + vargs.push_back("-vf"); + vargs.push_back("scale=" + std::to_string(w) + ":" + std::to_string(h)); + vargs.push_back("-f"); + vargs.push_back("rawvideo"); + vargs.push_back("-pix_fmt"); + vargs.push_back("rgb24"); + vargs.push_back("-"); + + pid_t vpid = -1; + int vfd = -1; + if (!media_detail::spawn_stdout_process(ffmpeg, vargs, vpid, vfd)) { + media_detail::close_fd_safe(video_wake_r_); + media_detail::close_fd_safe(video_wake_w_); + std::lock_guard lock(state_mutex_); + state_.error = "failed to spawn ffmpeg video decoder"; + return false; + } + + { + std::lock_guard lock(state_mutex_); + workers_stop_ = false; + state_.stopped = false; + state_.paused = false; + state_.playing = true; + state_.eof = false; + state_.position_sec = start_pos_sec; + state_.error.clear(); + } + { + std::lock_guard plock(proc_mutex_); + video_pid_ = vpid; + } + + video_thread_ = std::thread(&VideoPlayer::video_worker_loop, this, + start_pos_sec, w, h, fps, vfd, video_wake_r_, + vpid); + + if (want_audio) { + start_audio_worker_locked_ctrl(start_pos_sec); + } + return true; +} + +bool VideoPlayer::start_audio_worker_locked_ctrl(double start_pos_sec) { + stop_audio_worker_locked_ctrl(); + + const std::string ffmpeg = media_detail::resolve_executable("ffmpeg"); + if (ffmpeg.empty()) { + return false; + } + + std::string path; + std::function sink; + { + std::lock_guard lock(state_mutex_); + if (!state_.has_audio || state_.muted || !state_.playing) { + return false; + } + path = mp4_path_; + sink = pcm_sink_; + } + + if (!media_detail::create_wake_pipe(audio_wake_r_, audio_wake_w_)) { + return false; + } + + std::vector aargs = { + ffmpeg, + "-nostdin", + "-loglevel", + "error", + }; + if (start_pos_sec > 0.001) { + aargs.push_back("-ss"); + aargs.push_back(media_detail::format_seconds_c_locale(start_pos_sec)); + } + aargs.push_back("-i"); + aargs.push_back(path); + aargs.push_back("-vn"); + aargs.push_back("-f"); + aargs.push_back("s16le"); + aargs.push_back("-ac"); + aargs.push_back("1"); + aargs.push_back("-ar"); + aargs.push_back("44100"); + aargs.push_back("-"); + + if (sink) { + pid_t apid = -1; + int afd = -1; + if (!media_detail::spawn_stdout_process(ffmpeg, aargs, apid, afd)) { + media_detail::close_fd_safe(audio_wake_r_); + media_detail::close_fd_safe(audio_wake_w_); + return false; + } + { + std::lock_guard lock(state_mutex_); + audio_stop_ = false; + } + { + std::lock_guard plock(proc_mutex_); + audio_ffmpeg_pid_ = apid; + } + audio_thread_ = std::thread(&VideoPlayer::audio_worker_pcm_loop, this, + start_pos_sec, afd, audio_wake_r_, apid, + std::move(sink)); + return true; + } + + const std::string aplay = media_detail::resolve_executable("aplay"); + if (aplay.empty()) { + media_detail::close_fd_safe(audio_wake_r_); + media_detail::close_fd_safe(audio_wake_w_); + return false; + } + + int pcm_pipe[2] = {-1, -1}; + if (::pipe(pcm_pipe) != 0) { + media_detail::close_fd_safe(audio_wake_r_); + media_detail::close_fd_safe(audio_wake_w_); + return false; + } + + std::vector ff_argv; + ff_argv.reserve(aargs.size() + 1); + for (auto& s : aargs) ff_argv.push_back(const_cast(s.c_str())); + ff_argv.push_back(nullptr); + + std::vector p_args = { + aplay, "-f", "S16_LE", "-r", "44100", "-c", "1", "-q", + }; + std::vector ap_argv; + ap_argv.reserve(p_args.size() + 1); + for (auto& s : p_args) ap_argv.push_back(const_cast(s.c_str())); + ap_argv.push_back(nullptr); + + const pid_t ff_pid = ::fork(); + if (ff_pid < 0) { + ::close(pcm_pipe[0]); + ::close(pcm_pipe[1]); + media_detail::close_fd_safe(audio_wake_r_); + media_detail::close_fd_safe(audio_wake_w_); + return false; + } + if (ff_pid == 0) { + ::close(pcm_pipe[0]); + ::dup2(pcm_pipe[1], STDOUT_FILENO); + if (pcm_pipe[1] > 2) ::close(pcm_pipe[1]); + const int devnull = ::open("/dev/null", O_RDWR); + if (devnull >= 0) { + ::dup2(devnull, STDIN_FILENO); + ::dup2(devnull, STDERR_FILENO); + if (devnull > 2) ::close(devnull); + } + ::execvp(ffmpeg.c_str(), ff_argv.data()); + _exit(127); + } + + const pid_t ap_pid = ::fork(); + if (ap_pid < 0) { + ::close(pcm_pipe[0]); + ::close(pcm_pipe[1]); + pid_t tmp = ff_pid; + media_detail::kill_and_reap(tmp); + media_detail::close_fd_safe(audio_wake_r_); + media_detail::close_fd_safe(audio_wake_w_); + return false; + } + if (ap_pid == 0) { + ::close(pcm_pipe[1]); + ::dup2(pcm_pipe[0], STDIN_FILENO); + if (pcm_pipe[0] > 2) ::close(pcm_pipe[0]); + const int devnull = ::open("/dev/null", O_RDWR); + if (devnull >= 0) { + ::dup2(devnull, STDOUT_FILENO); + ::dup2(devnull, STDERR_FILENO); + if (devnull > 2) ::close(devnull); + } + ::execvp(aplay.c_str(), ap_argv.data()); + _exit(127); + } + + ::close(pcm_pipe[0]); + ::close(pcm_pipe[1]); + + { + std::lock_guard lock(state_mutex_); + audio_stop_ = false; + } + { + std::lock_guard plock(proc_mutex_); + audio_ffmpeg_pid_ = ff_pid; + aplay_pid_ = ap_pid; + } + audio_thread_ = std::thread(&VideoPlayer::audio_worker_aplay_loop, this, + audio_wake_r_, ff_pid, ap_pid); + return true; +} + +void VideoPlayer::stop_audio_worker_locked_ctrl() { + { + std::lock_guard lock(state_mutex_); + audio_stop_ = true; + } + pace_cv_.notify_all(); + media_detail::signal_wake_pipe(audio_wake_w_); + + { + std::lock_guard plock(proc_mutex_); + media_detail::kill_and_reap(aplay_pid_); + media_detail::kill_and_reap(audio_ffmpeg_pid_); + } + + if (audio_thread_.joinable()) { + audio_thread_.join(); + } + + media_detail::close_fd_safe(audio_wake_r_); + media_detail::close_fd_safe(audio_wake_w_); +} + +void VideoPlayer::stop_workers_locked_ctrl() { + { + std::lock_guard lock(state_mutex_); + workers_stop_ = true; + audio_stop_ = true; + } + pace_cv_.notify_all(); + media_detail::signal_wake_pipe(video_wake_w_); + media_detail::signal_wake_pipe(audio_wake_w_); + + { + std::lock_guard plock(proc_mutex_); + media_detail::kill_and_reap(video_pid_); + media_detail::kill_and_reap(aplay_pid_); + media_detail::kill_and_reap(audio_ffmpeg_pid_); + } + + if (video_thread_.joinable()) { + video_thread_.join(); + } + if (audio_thread_.joinable()) { + audio_thread_.join(); + } + + media_detail::close_fd_safe(video_wake_r_); + media_detail::close_fd_safe(video_wake_w_); + media_detail::close_fd_safe(audio_wake_r_); + media_detail::close_fd_safe(audio_wake_w_); +} + +void VideoPlayer::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) { + const size_t frame_bytes = + static_cast(frame_w) * static_cast(frame_h) * 3u; + const bool is_16_9 = + std::abs(static_cast(frame_w) / frame_h - (16.0 / 9.0)) < 0.05; + const auto frame_period = std::chrono::microseconds( + static_cast(std::llround(1000000.0 / std::max(1.0, fps)))); + const auto playback_t0 = std::chrono::steady_clock::now(); + + std::vector buf(frame_bytes); + uint64_t frame_idx = 0; + bool natural_eof = false; + + while (true) { + bool woken = false; + bool hit_eof = false; + if (!media_detail::read_exact_with_wake(stdout_fd, wake_fd, buf.data(), + frame_bytes, woken, hit_eof)) { + if (hit_eof && !woken) { + natural_eof = true; + } + break; + } + + if (frame_idx > 0) { + const auto target_time = playback_t0 + frame_period * frame_idx; + std::unique_lock lock(state_mutex_); + pace_cv_.wait_until(lock, target_time, [&]() { return workers_stop_; }); + if (workers_stop_) { + break; + } + } + + { + std::lock_guard fr_lock(frame_mutex_); + latest_frame_.seq = ++seq_counter_; + latest_frame_.width = frame_w; + latest_frame_.height = frame_h; + latest_frame_.is_16_9 = is_16_9; + latest_frame_.rgb24 = buf; + } + + { + std::lock_guard lock(state_mutex_); + if (workers_stop_) { + break; + } + const double cur_pos = start_pos_sec + static_cast(frame_idx) / fps; + state_.position_sec = state_.duration_sec > 0.0 + ? std::min(cur_pos, state_.duration_sec) + : cur_pos; + } + ++frame_idx; + } + + ::close(stdout_fd); + + bool stopped_by_caller = false; + { + std::lock_guard lock(state_mutex_); + stopped_by_caller = workers_stop_; + } + + int status = 0; + if (!stopped_by_caller && natural_eof) { + { + std::lock_guard plock(proc_mutex_); + if (video_pid_ == child_pid) { + video_pid_ = -1; + } + } + if (!media_detail::reap_pid_timeout(child_pid, 500, &status)) { + pid_t tmp = child_pid; + media_detail::kill_and_reap(tmp); + } + + std::lock_guard lock(state_mutex_); + if (!workers_stop_) { + state_.playing = false; + state_.paused = false; + state_.stopped = true; + state_.eof = true; + if (state_.duration_sec > 0.0) { + state_.position_sec = state_.duration_sec; + } + if (WIFEXITED(status) && WEXITSTATUS(status) != 0 && frame_idx == 0) { + state_.error = "ffmpeg video decoder exited with code " + + std::to_string(WEXITSTATUS(status)); + } + } + } +} + +void VideoPlayer::audio_worker_pcm_loop( + double /*start_pos_sec*/, + int stdout_fd, + int wake_fd, + pid_t child_pid, + std::function sink) { + static constexpr size_t kChunkSamples = 2048; + std::vector samples(kChunkSamples); + uint8_t* raw_bytes = reinterpret_cast(samples.data()); + size_t leftover = 0; + const auto t0 = std::chrono::steady_clock::now(); + uint64_t total_samples = 0; + + while (true) { + pollfd pfds[2] = { + {stdout_fd, POLLIN, 0}, + {wake_fd, POLLIN, 0}, + }; + const int rc = ::poll(pfds, 2, -1); + if (rc < 0) { + if (errno == EINTR) continue; + break; + } + if (pfds[1].revents & (POLLIN | POLLHUP | POLLERR)) { + break; + } + if (pfds[0].revents & (POLLIN | POLLHUP | POLLERR)) { + const ssize_t r = ::read( + stdout_fd, raw_bytes + leftover, + kChunkSamples * sizeof(int16_t) - leftover); + if (r <= 0) { + if (r < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) { + continue; + } + break; + } + const size_t total_bytes = leftover + static_cast(r); + const size_t count = total_bytes / sizeof(int16_t); + const size_t next_leftover = total_bytes % sizeof(int16_t); + const uint8_t carry_byte = + next_leftover > 0 ? raw_bytes[total_bytes - 1] : 0; + if (count > 0 && sink) { + sink(samples.data(), count); + total_samples += count; + + // Keep audio queued ~150ms ahead of playback without flooding SDL queue + const double audio_sec = static_cast(total_samples) / 44100.0; + if (audio_sec > 0.15) { + const auto target = + t0 + std::chrono::microseconds(static_cast( + std::llround((audio_sec - 0.15) * 1000000.0))); + std::unique_lock lock(state_mutex_); + pace_cv_.wait_until(lock, target, + [&]() { return workers_stop_ || audio_stop_; }); + if (workers_stop_ || audio_stop_) { + break; + } + } + } + leftover = next_leftover; + if (leftover > 0) { + raw_bytes[0] = carry_byte; + } + } + } + + ::close(stdout_fd); + bool stopped = false; + { + std::lock_guard lock(state_mutex_); + stopped = workers_stop_ || audio_stop_; + } + if (!stopped) { + std::lock_guard plock(proc_mutex_); + if (audio_ffmpeg_pid_ == child_pid) { + audio_ffmpeg_pid_ = -1; + media_detail::reap_pid_timeout(child_pid, 400, nullptr); + } + } +} + +void VideoPlayer::audio_worker_aplay_loop(int wake_fd, + pid_t ffmpeg_pid, + pid_t aplay_pid) { + while (true) { + { + std::lock_guard lock(state_mutex_); + if (workers_stop_ || audio_stop_) { + break; + } + } + int st_ap = 0; + const pid_t r_ap = ::waitpid(aplay_pid, &st_ap, WNOHANG); + if (r_ap == aplay_pid || (r_ap < 0 && errno == ECHILD)) { + std::lock_guard plock(proc_mutex_); + if (aplay_pid_ == aplay_pid) { + aplay_pid_ = -1; + } + if (audio_ffmpeg_pid_ == ffmpeg_pid) { + media_detail::kill_and_reap(audio_ffmpeg_pid_); + } + break; + } + + pollfd pfd{wake_fd, POLLIN, 0}; + const int rc = ::poll(&pfd, 1, 50); + if (rc > 0 && (pfd.revents & (POLLIN | POLLHUP | POLLERR))) { + break; + } + } +} + +} // namespace cz diff --git a/app/src/video_player.hpp b/app/src/video_player.hpp new file mode 100644 index 0000000..9b00cc5 --- /dev/null +++ b/app/src/video_player.hpp @@ -0,0 +1,144 @@ +#pragma once + +#include "camera_backend.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +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& 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& 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 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 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 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 diff --git a/app/tests/test_timelapse_and_gallery.cpp b/app/tests/test_timelapse_and_gallery.cpp new file mode 100644 index 0000000..fc5f919 --- /dev/null +++ b/app/tests/test_timelapse_and_gallery.cpp @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(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(in)), + std::istreambuf_iterator()); +} + +bool create_sample_jpeg(const std::string& path, int w, int h, uint8_t seed) { + std::vector rgb(static_cast(w) * static_cast(h) * 3u); + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + const size_t idx = (static_cast(y) * w + x) * 3u; + rgb[idx + 0] = static_cast((x * 3 + seed) & 0xFF); + rgb[idx + 1] = static_cast((y * 5 + seed * 2) & 0xFF); + rgb[idx + 2] = static_cast(((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 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& args) { + const std::string exe = find_tool_path("ffmpeg"); + std::vector full_args; + full_args.push_back(exe); + full_args.insert(full_args.end(), args.begin(), args.end()); + + std::vector argv_ptrs; + argv_ptrs.reserve(full_args.size() + 1); + for (auto& a : full_args) { + argv_ptrs.push_back(const_cast(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& 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& 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(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(i))); + } + std::atomic 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(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_/ 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_.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(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(f1.width) * static_cast(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 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; +}