fix: resolve final whole-branch review findings

This commit is contained in:
2026-11-19 18:30:26 -05:00
parent a127c338d4
commit e3bd5bf615
12 changed files with 744 additions and 137 deletions

View File

@@ -807,18 +807,22 @@ struct AppView::Impl {
constexpr int kVfH = 170;
canvas.fill_rect(vf_x, 0, kVfW, kVfH, pal.viewfinder_surround);
const bool show_live_frame =
state.backend_ready && !state.backend_paused && live_frame != nullptr &&
!live_frame->rgb24.empty() && live_frame->width > 0 &&
live_frame->height > 0;
const bool is_16_9 =
(state.mode == AppMode::Video) ||
(state.mode == AppMode::Timelapse &&
state.config.timelapse_resolution == "1080p") ||
(live_frame != nullptr && live_frame->is_16_9);
(show_live_frame && live_frame->is_16_9);
const int feed_w = kVfW;
const int feed_h = is_16_9 ? 127 : kVfH;
const int feed_y = is_16_9 ? 21 : 0;
if (live_frame != nullptr && !live_frame->rgb24.empty() &&
live_frame->width > 0 && live_frame->height > 0) {
if (show_live_frame) {
scaled_vf.resize(static_cast<size_t>(feed_w) * static_cast<size_t>(feed_h) *
3u);
const float loupe =

View File

@@ -0,0 +1,39 @@
#pragma once
#include <cstdint>
#include <unordered_set>
namespace cz {
/// Suppresses Linux evdev auto-repeat events (value == 2) for any key whose
/// initial press (value == 1) arrived while the display was dimmed.
class EvdevRepeatGuard {
public:
bool should_dispatch(uint16_t code, int32_t value, bool is_dimmed) {
if (value == 0) {
suppressed_codes_.erase(code);
return false;
}
if (value == 1) {
if (is_dimmed) {
suppressed_codes_.insert(code);
} else {
suppressed_codes_.erase(code);
}
return true;
}
if (value == 2) {
if (is_dimmed) {
suppressed_codes_.insert(code);
return true;
}
return suppressed_codes_.count(code) == 0;
}
return false;
}
private:
std::unordered_set<uint16_t> suppressed_codes_;
};
} // namespace cz

View File

@@ -1,5 +1,6 @@
#include "app_ui.hpp"
#include "camera_backend.hpp"
#include "evdev_repeat_guard.hpp"
#include "fb_blit.hpp"
#include "storage.hpp"
#include "ui_controller.hpp"
@@ -81,6 +82,89 @@ struct CliOptions {
std::string rail_override;
};
struct RenderDirtyTracker {
uint64_t gal_seq = 0;
double vp_pos = -1.0;
bool vp_playing = false;
bool flash = false;
bool dimmed = false;
bool backend_ready = false;
bool backend_paused = false;
bool tl_running = false;
int tl_shots = 0;
int tl_next = 0;
int tl_elapsed = 0;
int vid_sec = 0;
int timer_sec = 0;
int comp_cur = 0;
std::string toast;
cz::OverlayModal modal = cz::OverlayModal::None;
void sync(const cz::UiState& st, uint64_t cur_gal_seq) {
gal_seq = cur_gal_seq;
vp_pos = st.video_player.position_sec;
vp_playing = st.video_player.playing;
flash = st.capture_flash_active;
dimmed = st.timelapse_dimmed;
backend_ready = st.backend_ready;
backend_paused = st.backend_paused;
tl_running = st.timelapse.running;
tl_shots = st.timelapse.shots_taken;
tl_next = st.timelapse.next_shot_in_sec;
tl_elapsed = st.timelapse.elapsed_sec;
vid_sec = st.video_elapsed_sec;
timer_sec = st.timer_remaining_sec;
comp_cur = st.timelapse.compile_current;
toast = st.toast_message;
modal = st.modal;
}
bool changed(const cz::UiState& st, uint64_t cur_gal_seq) const {
return cur_gal_seq != gal_seq ||
st.video_player.position_sec != vp_pos ||
st.video_player.playing != vp_playing ||
st.capture_flash_active != flash ||
st.timelapse_dimmed != dimmed ||
st.backend_ready != backend_ready ||
st.backend_paused != backend_paused ||
st.timelapse.running != tl_running ||
st.timelapse.shots_taken != tl_shots ||
st.timelapse.next_shot_in_sec != tl_next ||
st.timelapse.elapsed_sec != tl_elapsed ||
st.video_elapsed_sec != vid_sec ||
st.timer_remaining_sec != timer_sec ||
st.timelapse.compile_current != comp_cur ||
st.toast_message != toast ||
st.modal != modal;
}
};
void poll_live_frame_state(cz::UiController& ctrl,
uint64_t& last_live_seq,
cz::PreviewFrame& live_frame,
bool& dirty) {
const auto& st = ctrl.state();
if (!st.backend_ready || st.backend_paused) {
if (!live_frame.rgb24.empty()) {
live_frame = cz::PreviewFrame{};
dirty = true;
}
return;
}
if (ctrl.backend() && st.modal != cz::OverlayModal::Gallery) {
if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) {
last_live_seq = live_frame.seq;
dirty = true;
}
}
}
const cz::PreviewFrame* effective_live_frame(
const cz::UiState& st,
const cz::PreviewFrame& live_frame) {
return (st.backend_ready && !st.backend_paused) ? &live_frame : nullptr;
}
int run_render_test(const CliOptions& cli) {
ScopedTempDir temp_dir;
std::string eff_out = cli.output_dir;
@@ -149,7 +233,8 @@ int run_render_test(const CliOptions& cli) {
cz::AppView view;
view.apply_theme(ctrl.state().theme);
view.render(ctrl.state(), &live_frame, ctrl.gallery_preview());
view.render(ctrl.state(), effective_live_frame(ctrl.state(), live_frame),
ctrl.gallery_preview());
const bool ok = view.save_ppm(cli.render_test_path);
ctrl.shutdown();
@@ -317,30 +402,23 @@ int run_device_loop(cz::UiController& ctrl, cz::AppView& view) {
cz::PreviewFrame live_frame;
uint64_t last_live_seq = 0;
uint64_t last_gal_seq = 0;
double last_vp_pos = -1.0;
bool last_vp_playing = false;
view.apply_theme(ctrl.state().theme);
if (ctrl.backend()) {
if (ctrl.backend() && ctrl.state().backend_ready &&
!ctrl.state().backend_paused) {
if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) {
last_live_seq = live_frame.seq;
}
}
view.render(ctrl.state(), &live_frame, ctrl.gallery_preview());
const cz::PreviewFrame* init_gp = ctrl.gallery_preview();
view.render(ctrl.state(), effective_live_frame(ctrl.state(), live_frame),
init_gp);
blit_fbdev(fb_mem, map_size, vinfo, finfo, view.pixels());
bool shift_down = false;
bool prev_flash = ctrl.state().capture_flash_active;
bool prev_dimmed = ctrl.state().timelapse_dimmed;
int prev_tl_shots = ctrl.state().timelapse.shots_taken;
int prev_tl_next = ctrl.state().timelapse.next_shot_in_sec;
int prev_tl_elapsed = ctrl.state().timelapse.elapsed_sec;
int prev_vid_sec = ctrl.state().video_elapsed_sec;
int prev_timer_sec = ctrl.state().timer_remaining_sec;
int prev_comp_cur = ctrl.state().timelapse.compile_current;
std::string prev_toast = ctrl.state().toast_message;
cz::OverlayModal prev_modal = ctrl.state().modal;
cz::EvdevRepeatGuard repeat_guard;
RenderDirtyTracker dirty_tracker;
dirty_tracker.sync(ctrl.state(), init_gp ? init_gp->seq : 0);
while (!ctrl.should_quit() && !g_signal_stop) {
bool dirty = false;
@@ -380,7 +458,8 @@ int run_device_loop(cz::UiController& ctrl, cz::AppView& view) {
shift_down = (ev.value != 0);
continue;
}
if (ev.value != 1 && ev.value != 2) {
if (!repeat_guard.should_dispatch(
ev.code, ev.value, ctrl.state().timelapse_dimmed)) {
continue;
}
const uint64_t now = steady_now_ms();
@@ -447,46 +526,18 @@ int run_device_loop(cz::UiController& ctrl, cz::AppView& view) {
const uint64_t now = steady_now_ms();
ctrl.tick(now);
if (ctrl.backend() && ctrl.state().modal != cz::OverlayModal::Gallery) {
if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) {
last_live_seq = live_frame.seq;
dirty = true;
}
}
poll_live_frame_state(ctrl, last_live_seq, live_frame, dirty);
const cz::PreviewFrame* gp = ctrl.gallery_preview();
const uint64_t gal_seq = gp ? gp->seq : 0;
const auto& st = ctrl.state();
if (gal_seq != last_gal_seq || st.video_player.position_sec != last_vp_pos ||
st.video_player.playing != last_vp_playing ||
st.capture_flash_active != prev_flash ||
st.timelapse_dimmed != prev_dimmed ||
st.timelapse.shots_taken != prev_tl_shots ||
st.timelapse.next_shot_in_sec != prev_tl_next ||
st.timelapse.elapsed_sec != prev_tl_elapsed ||
st.video_elapsed_sec != prev_vid_sec ||
st.timer_remaining_sec != prev_timer_sec ||
st.timelapse.compile_current != prev_comp_cur ||
st.toast_message != prev_toast || st.modal != prev_modal) {
if (dirty_tracker.changed(st, gal_seq)) {
dirty = true;
}
if (dirty) {
last_gal_seq = gal_seq;
last_vp_pos = st.video_player.position_sec;
last_vp_playing = st.video_player.playing;
prev_flash = st.capture_flash_active;
prev_dimmed = st.timelapse_dimmed;
prev_tl_shots = st.timelapse.shots_taken;
prev_tl_next = st.timelapse.next_shot_in_sec;
prev_tl_elapsed = st.timelapse.elapsed_sec;
prev_vid_sec = st.video_elapsed_sec;
prev_timer_sec = st.timer_remaining_sec;
prev_comp_cur = st.timelapse.compile_current;
prev_toast = st.toast_message;
prev_modal = st.modal;
view.render(st, &live_frame, gp);
dirty_tracker.sync(st, gal_seq);
view.render(st, effective_live_frame(st, live_frame), gp);
blit_fbdev(fb_mem, map_size, vinfo, finfo, view.pixels());
}
}
@@ -573,17 +624,17 @@ int run_sdl_loop(cz::UiController& ctrl, cz::AppView& view, int scale) {
cz::PreviewFrame live_frame;
uint64_t last_live_seq = 0;
uint64_t last_gal_seq = 0;
double last_vp_pos = -1.0;
bool last_vp_playing = false;
view.apply_theme(ctrl.state().theme);
if (ctrl.backend()) {
if (ctrl.backend() && ctrl.state().backend_ready &&
!ctrl.state().backend_paused) {
if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) {
last_live_seq = live_frame.seq;
}
}
view.render(ctrl.state(), &live_frame, ctrl.gallery_preview());
const cz::PreviewFrame* init_gp = ctrl.gallery_preview();
view.render(ctrl.state(), effective_live_frame(ctrl.state(), live_frame),
init_gp);
auto present = [&]() {
SDL_UpdateTexture(texture, nullptr, view.pixels(),
@@ -595,16 +646,8 @@ int run_sdl_loop(cz::UiController& ctrl, cz::AppView& view, int scale) {
present();
bool running = true;
bool prev_flash = ctrl.state().capture_flash_active;
bool prev_dimmed = ctrl.state().timelapse_dimmed;
int prev_tl_shots = ctrl.state().timelapse.shots_taken;
int prev_tl_next = ctrl.state().timelapse.next_shot_in_sec;
int prev_tl_elapsed = ctrl.state().timelapse.elapsed_sec;
int prev_vid_sec = ctrl.state().video_elapsed_sec;
int prev_timer_sec = ctrl.state().timer_remaining_sec;
int prev_comp_cur = ctrl.state().timelapse.compile_current;
std::string prev_toast = ctrl.state().toast_message;
cz::OverlayModal prev_modal = ctrl.state().modal;
RenderDirtyTracker dirty_tracker;
dirty_tracker.sync(ctrl.state(), init_gp ? init_gp->seq : 0);
while (running && !ctrl.should_quit() && !g_signal_stop) {
bool dirty = false;
@@ -685,54 +728,27 @@ int run_sdl_loop(cz::UiController& ctrl, cz::AppView& view, int scale) {
const uint64_t now = steady_now_ms();
ctrl.tick(now);
if (ctrl.backend() && ctrl.state().modal != cz::OverlayModal::Gallery) {
if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) {
last_live_seq = live_frame.seq;
dirty = true;
}
}
poll_live_frame_state(ctrl, last_live_seq, live_frame, dirty);
const auto& st = ctrl.state();
if (audio_dev != 0) {
if ((!st.video_player.playing && last_vp_playing) ||
if ((!st.video_player.playing && dirty_tracker.vp_playing) ||
(st.video_player.playing &&
std::abs(st.video_player.position_sec - last_vp_pos) > 0.45)) {
std::abs(st.video_player.position_sec - dirty_tracker.vp_pos) >
0.45)) {
SDL_ClearQueuedAudio(audio_dev);
}
}
const cz::PreviewFrame* gp = ctrl.gallery_preview();
const uint64_t gal_seq = gp ? gp->seq : 0;
if (gal_seq != last_gal_seq || st.video_player.position_sec != last_vp_pos ||
st.video_player.playing != last_vp_playing ||
st.capture_flash_active != prev_flash ||
st.timelapse_dimmed != prev_dimmed ||
st.timelapse.shots_taken != prev_tl_shots ||
st.timelapse.next_shot_in_sec != prev_tl_next ||
st.timelapse.elapsed_sec != prev_tl_elapsed ||
st.video_elapsed_sec != prev_vid_sec ||
st.timer_remaining_sec != prev_timer_sec ||
st.timelapse.compile_current != prev_comp_cur ||
st.toast_message != prev_toast || st.modal != prev_modal) {
if (dirty_tracker.changed(st, gal_seq)) {
dirty = true;
}
if (dirty) {
last_gal_seq = gal_seq;
last_vp_pos = st.video_player.position_sec;
last_vp_playing = st.video_player.playing;
prev_flash = st.capture_flash_active;
prev_dimmed = st.timelapse_dimmed;
prev_tl_shots = st.timelapse.shots_taken;
prev_tl_next = st.timelapse.next_shot_in_sec;
prev_tl_elapsed = st.timelapse.elapsed_sec;
prev_vid_sec = st.video_elapsed_sec;
prev_timer_sec = st.timer_remaining_sec;
prev_comp_cur = st.timelapse.compile_current;
prev_toast = st.toast_message;
prev_modal = st.modal;
view.render(st, &live_frame, gp);
dirty_tracker.sync(st, gal_seq);
view.render(st, effective_live_frame(st, live_frame), gp);
present();
}
}

View File

@@ -58,7 +58,7 @@ std::string current_timestamp_compact() {
const std::time_t now = std::time(nullptr);
struct tm tm_now {};
::localtime_r(&now, &tm_now);
char buf[32];
char buf[64];
std::snprintf(buf, sizeof(buf), "%04d%02d%02d_%02d%02d%02d",
tm_now.tm_year + 1900, tm_now.tm_mon + 1, tm_now.tm_mday,
tm_now.tm_hour, tm_now.tm_min, tm_now.tm_sec);

View File

@@ -50,7 +50,7 @@ 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];
char buf[64];
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);

View File

@@ -220,6 +220,7 @@ bool UiController::init(uint64_t now_ms) {
return true;
}
last_now_ms_ = now_ms;
state_.config = load_config(opts_.config_path);
persisted_output_dir_ = state_.config.output_dir;
@@ -278,6 +279,8 @@ void UiController::shutdown() {
if (backend_) {
backend_->stop();
}
state_.backend_ready = false;
state_.backend_paused = false;
initialized_ = false;
}
@@ -351,9 +354,13 @@ bool UiController::reconfigure_backend(std::string& out_err) {
}
void UiController::sync_backend_status() {
const bool was_ready = state_.backend_ready;
if (!backend_) {
state_.backend_ready = false;
state_.backend_paused = false;
if (initialized_ && was_ready) {
set_toast("Camera offline", true, last_now_ms_);
}
return;
}
const BackendHealth h = backend_->status();
@@ -364,6 +371,15 @@ void UiController::sync_backend_status() {
} else if (h.ready) {
state_.backend_error.clear();
}
if (initialized_ && was_ready && !h.ready && !state_.backend_paused) {
const std::string msg =
!h.last_error.empty()
? h.last_error
: (!state_.backend_error.empty() ? state_.backend_error
: "Camera offline");
set_toast(msg, true, last_now_ms_);
}
}
void UiController::set_toast(const std::string& message,
@@ -505,6 +521,7 @@ void UiController::tick(uint64_t now_ms) {
if (!initialized_) {
init(now_ms);
}
last_now_ms_ = now_ms;
if (state_.capture_flash_active && now_ms >= flash_until_ms_) {
state_.capture_flash_active = false;
@@ -557,6 +574,9 @@ void UiController::tick(uint64_t now_ms) {
if (!state_.timelapse.running) {
backlight_.restore();
state_.timelapse_dimmed = false;
if (state_.modal == OverlayModal::TimelapseStopConfirm) {
state_.modal = OverlayModal::None;
}
refresh_storage_stats();
if (state_.timelapse.needs_compile && !compile_in_flight_.load()) {
@@ -1115,6 +1135,7 @@ bool UiController::handle_key(char ch, KeyCode code, uint64_t now_ms) {
init(now_ms);
}
last_now_ms_ = now_ms;
last_activity_ms_ = now_ms;
// Safe Wake Rule (Review Focus #2): any key while dimmed ONLY wakes backlight.

View File

@@ -217,6 +217,7 @@ class UiController {
bool quit_ = false;
bool capture_flash_pending_ = false;
uint64_t last_now_ms_ = 0;
uint64_t last_activity_ms_ = 0;
uint64_t timer_target_ms_ = 0;
uint64_t flash_until_ms_ = 0;

View File

@@ -1,5 +1,6 @@
#include "app_ui.hpp"
#include "config.hpp"
#include "evdev_repeat_guard.hpp"
#include "sim_backend.hpp"
#include "storage.hpp"
#include "ui_controller.hpp"
@@ -149,6 +150,74 @@ class SpyCameraBackend final : public cz::ICameraBackend {
cz::SimCameraBackend inner_;
};
class DropSimBackend final : public cz::ICameraBackend {
public:
bool start(const cz::CameraStreamSpec& initial_spec,
std::string& out_err) override {
if (fail_start) {
out_err = "Simulated camera start failure";
return false;
}
force_offline = false;
forced_error.clear();
return inner_.start(initial_spec, out_err);
}
void stop() override { inner_.stop(); }
bool reconfigure(const cz::CameraStreamSpec& spec,
std::string& out_err) override {
return inner_.reconfigure(spec, out_err);
}
bool set_controls(float zoom, float ev, std::string& out_err) override {
return inner_.set_controls(zoom, ev, out_err);
}
bool pause(std::string& out_err) override { return inner_.pause(out_err); }
bool resume(std::string& out_err) override { return inner_.resume(out_err); }
bool copy_latest_preview(uint64_t last_seen_seq,
cz::PreviewFrame& out_frame) override {
return inner_.copy_latest_preview(last_seen_seq, out_frame);
}
cz::StillCaptureResult capture_still(const std::string& tmp_jpeg_path,
int width,
int height) override {
return inner_.capture_still(tmp_jpeg_path, width, height);
}
bool start_video(const cz::VideoSpec& spec, std::string& out_err) override {
return inner_.start_video(spec, out_err);
}
cz::VideoStopResult stop_video() override { return inner_.stop_video(); }
cz::BackendHealth status() const override {
cz::BackendHealth h = inner_.status();
if (force_offline) {
h.ready = false;
h.recording = false;
h.last_error = forced_error;
}
return h;
}
void simulate_drop(const std::string& err) {
force_offline = true;
forced_error = err;
}
bool fail_start = false;
bool force_offline = false;
std::string forced_error;
private:
cz::SimCameraBackend inner_;
};
void test_photo_controls_zoom_loupe_filters_and_timer() {
TempDir tmp("photo");
const std::string cfg_path = tmp.path + "/config.json";
@@ -791,6 +860,249 @@ void test_text_input_timelapse_custom_recovery_and_modal_renders() {
}
}
void test_backend_drop_toast_and_stale_live_frame_rendering() {
TempDir tmp("backend_drop");
const std::string cfg_path = tmp.path + "/config.json";
const std::string out_dir = tmp.path + "/out";
assert(cz::mkdir_p(out_dir));
cz::AppConfig cfg;
cfg.output_dir = out_dir;
assert(cz::save_config(cfg, cfg_path));
cz::UiControllerOptions opts;
opts.config_path = cfg_path;
opts.backlight_sysfs_root = tmp.path + "/no_backlight";
opts.skip_startup_recovery_scan = true;
// 1. Initial startup failure surfaces startup toast once without spurious repeats
{
auto fail_owned = std::make_unique<DropSimBackend>();
fail_owned->fail_start = true;
cz::UiController ctrl(std::move(fail_owned), opts);
uint64_t now = 1000;
assert(ctrl.init(now));
assert(!ctrl.state().backend_ready);
assert(ctrl.state().toast_is_error);
assert(ctrl.state().toast_message == "Simulated camera start failure");
now += 4000;
ctrl.tick(now);
assert(ctrl.state().toast_message.empty());
}
// 2. Unexpected true -> false drop emits error toast, and offline/paused
// render cleanly even when a non-null stale live_frame is passed.
auto drop_owned = std::make_unique<DropSimBackend>();
DropSimBackend* drop = drop_owned.get();
cz::UiController ctrl(std::move(drop_owned), opts);
uint64_t now = 1000;
assert(ctrl.init(now));
assert(ctrl.state().backend_ready);
assert(!ctrl.state().backend_paused);
assert(ctrl.state().toast_message.empty());
cz::PreviewFrame live;
assert(ctrl.backend()->copy_latest_preview(0, live));
assert(!live.rgb24.empty());
cz::AppView view;
view.apply_theme(ctrl.state().theme);
view.render(ctrl.state(), &live, nullptr);
const std::vector<uint32_t> live_pixels(
view.pixels(),
view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight);
// Stale 16:9 flag in stale live_frame must not affect offline/paused Photo layout
cz::PreviewFrame stale_16_9 = live;
stale_16_9.is_16_9 = true;
cz::UiState offline_state = ctrl.state();
offline_state.backend_ready = false;
offline_state.backend_paused = false;
view.render(offline_state, &live, nullptr);
const std::vector<uint32_t> offline_with_4_3(
view.pixels(),
view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight);
view.render(offline_state, &stale_16_9, nullptr);
const std::vector<uint32_t> offline_with_stale(
view.pixels(),
view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight);
view.render(offline_state, nullptr, nullptr);
const std::vector<uint32_t> offline_with_null(
view.pixels(),
view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight);
assert(offline_with_4_3 != live_pixels);
assert(offline_with_4_3 == offline_with_null);
assert(offline_with_stale != live_pixels);
assert(offline_with_stale == offline_with_null);
cz::UiState paused_state = ctrl.state();
paused_state.backend_ready = true;
paused_state.backend_paused = true;
view.render(paused_state, &live, nullptr);
const std::vector<uint32_t> paused_with_4_3(
view.pixels(),
view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight);
view.render(paused_state, &stale_16_9, nullptr);
const std::vector<uint32_t> paused_with_stale(
view.pixels(),
view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight);
view.render(paused_state, nullptr, nullptr);
const std::vector<uint32_t> paused_with_null(
view.pixels(),
view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight);
assert(paused_with_4_3 != live_pixels);
assert(paused_with_4_3 == paused_with_null);
assert(paused_with_stale != live_pixels);
assert(paused_with_stale != offline_with_stale);
assert(paused_with_stale == paused_with_null);
// Trigger unexpected backend drop with descriptive backend error
drop->simulate_drop("czcamera-cam exited unexpectedly (code 1)");
now += 100;
ctrl.tick(now);
assert(!ctrl.state().backend_ready);
assert(ctrl.state().toast_is_error);
assert(ctrl.state().toast_message ==
"czcamera-cam exited unexpectedly (code 1)");
// Recover via [R], verify fallback "Camera offline" when last_error is empty
now += 100;
ctrl.handle_key('r', cz::KeyCode::Char, now);
assert(ctrl.state().backend_ready);
assert(ctrl.state().toast_message == "Camera recovered");
now += 4000;
ctrl.tick(now);
assert(ctrl.state().toast_message.empty());
drop->simulate_drop("");
now += 100;
ctrl.tick(now);
assert(!ctrl.state().backend_ready);
assert(ctrl.state().toast_is_error);
assert(ctrl.state().toast_message == "Camera offline");
// Recover and confirm shutdown() leaves no spurious error toast
now += 100;
ctrl.handle_key('r', cz::KeyCode::Char, now);
assert(ctrl.state().backend_ready);
now += 4000;
ctrl.tick(now);
assert(ctrl.state().toast_message.empty());
ctrl.shutdown();
assert(!ctrl.state().backend_ready);
assert(ctrl.state().toast_message.empty());
}
void test_timelapse_photos_auto_finish_clears_stop_confirm_modal() {
TempDir tmp("tl_stop_confirm_autofinish");
const std::string cfg_path = tmp.path + "/config.json";
const std::string out_dir = tmp.path + "/out";
assert(cz::mkdir_p(out_dir));
cz::AppConfig cfg;
cfg.output_dir = out_dir;
cfg.timelapse_output_mode = "photos";
cfg.timelapse_interval_sec = 2;
cfg.timelapse_stop_mode = "shots";
cfg.timelapse_stop_value = 2;
assert(cz::save_config(cfg, cfg_path));
cz::UiControllerOptions opts;
opts.config_path = cfg_path;
opts.backlight_sysfs_root = tmp.path + "/no_backlight";
opts.skip_startup_recovery_scan = true;
cz::UiController ctrl(std::make_unique<cz::SimCameraBackend>(), opts);
uint64_t now = 1000;
assert(ctrl.init(now));
ctrl.handle_key('3', cz::KeyCode::Char, now);
assert(ctrl.state().mode == cz::AppMode::Timelapse);
ctrl.handle_key(0, cz::KeyCode::Enter, now);
ctrl.tick(now);
assert(ctrl.state().timelapse.running);
assert(ctrl.state().timelapse.shots_taken == 1);
// Open Stop Confirm modal while Photos-mode timelapse is active
now += 100;
ctrl.handle_key(0, cz::KeyCode::Esc, now);
assert(ctrl.state().modal == cz::OverlayModal::TimelapseStopConfirm);
// Tick past the 2-shot stop limit; modal must clear automatically
now += 2500;
ctrl.tick(now);
assert(!ctrl.state().timelapse.running);
assert(!ctrl.state().timelapse.needs_compile);
assert(ctrl.state().timelapse.shots_taken == 2);
assert(ctrl.state().modal == cz::OverlayModal::None);
}
void test_evdev_repeat_guard_suppresses_wake_key_repeats() {
TempDir tmp("evdev_repeat_guard");
const std::string cfg_path = tmp.path + "/config.json";
const std::string out_dir = tmp.path + "/out";
const std::string bl_root = tmp.path + "/backlight";
const std::string lcd0 = bl_root + "/lcd0";
assert(cz::mkdir_p(out_dir));
assert(cz::mkdir_p(lcd0));
write_text(lcd0 + "/brightness", "128\n");
write_text(lcd0 + "/max_brightness", "255\n");
cz::AppConfig cfg;
cfg.output_dir = out_dir;
cfg.timelapse_dim_sec = 5;
cfg.timelapse_interval_sec = 4;
cfg.timelapse_output_mode = "photos";
assert(cz::save_config(cfg, cfg_path));
cz::UiControllerOptions opts;
opts.config_path = cfg_path;
opts.backlight_sysfs_root = bl_root;
opts.skip_startup_recovery_scan = true;
cz::UiController ctrl(std::make_unique<cz::SimCameraBackend>(), opts);
uint64_t now = 1000;
assert(ctrl.init(now));
ctrl.handle_key('3', cz::KeyCode::Char, now);
ctrl.handle_key(0, cz::KeyCode::Enter, now);
ctrl.tick(now);
assert(ctrl.state().timelapse.running);
now += 6000;
ctrl.tick(now);
assert(ctrl.state().timelapse_dimmed);
cz::EvdevRepeatGuard guard;
constexpr uint16_t kKeyEsc = 1;
constexpr uint16_t kKeyDown = 108;
// Initial press (value=1) while dimmed wakes LCD and arms repeat suppression
assert(guard.should_dispatch(kKeyEsc, 1, ctrl.state().timelapse_dimmed));
ctrl.handle_key(0, cz::KeyCode::Esc, now);
assert(!ctrl.state().timelapse_dimmed);
assert(ctrl.state().modal == cz::OverlayModal::None);
// Kernel auto-repeats (value=2) while key stays held must be suppressed
now += 250;
assert(!guard.should_dispatch(kKeyEsc, 2, ctrl.state().timelapse_dimmed));
assert(!guard.should_dispatch(kKeyEsc, 2, ctrl.state().timelapse_dimmed));
assert(ctrl.state().modal == cz::OverlayModal::None);
// Normal repeats for a key pressed while awake still dispatch
assert(guard.should_dispatch(kKeyDown, 1, ctrl.state().timelapse_dimmed));
assert(guard.should_dispatch(kKeyDown, 2, ctrl.state().timelapse_dimmed));
assert(!guard.should_dispatch(kKeyDown, 0, ctrl.state().timelapse_dimmed));
// Key release (value=0) clears suppression; next fresh press opens modal
assert(!guard.should_dispatch(kKeyEsc, 0, ctrl.state().timelapse_dimmed));
now += 50;
assert(guard.should_dispatch(kKeyEsc, 1, ctrl.state().timelapse_dimmed));
ctrl.handle_key(0, cz::KeyCode::Esc, now);
assert(ctrl.state().modal == cz::OverlayModal::TimelapseStopConfirm);
}
} // namespace
int main() {
@@ -800,6 +1112,9 @@ int main() {
test_timelapse_dimmed_safe_wake();
test_settings_dir_picker_camera_orient_and_gallery_delete();
test_text_input_timelapse_custom_recovery_and_modal_renders();
test_backend_drop_toast_and_stale_live_frame_rendering();
test_timelapse_photos_auto_finish_clears_stop_confirm_modal();
test_evdev_repeat_guard_suppresses_wake_key_repeats();
std::cout << "test_ui_controller: ALL PASSED\n";
return 0;
}

View File

@@ -3,7 +3,6 @@
from __future__ import annotations
import os
import shlex
import struct
import threading
import time
@@ -143,6 +142,26 @@ def _is_16_9_mode(mode: str, main_w: int, main_h: int) -> bool:
return False
class _FfmpegOutputTarget(str):
"""str subclass for picamera2.outputs.FfmpegOutput preserving path tokens.
Upstream FfmpegOutput.start() parses output_filename with plain str.split()
and no shell, so paths containing spaces or shlex quotes would break.
"""
_tokens: tuple[str, ...]
def __new__(cls, *tokens: str) -> "_FfmpegOutputTarget":
obj = super().__new__(cls, " ".join(tokens))
obj._tokens = tuple(tokens)
return obj
def split(self, sep: Optional[str] = None, maxsplit: int = -1) -> list[str]:
if sep is None and maxsplit == -1:
return list(self._tokens)
return super().split(sep, maxsplit)
def _probe_alsa_available() -> bool:
cards_path = "/proc/asound/cards"
if not os.path.exists(cards_path):
@@ -652,7 +671,7 @@ class Picam2Worker:
self._ensure_picamera2_imports()
# Ruling 3: staging files end in .mp4.part so ffmpeg needs -f mp4 explicitly.
output_target = f"-f mp4 -movflags +faststart {shlex.quote(tmp_path)}"
output_target = _FfmpegOutputTarget("-f", "mp4", "-movflags", "+faststart", tmp_path)
audio_recorded = False
if audio:

View File

@@ -59,7 +59,7 @@ class FramePipeWriter:
self._fd = frame_fd
self._owns_fd = owns_fd
self._cond = threading.Condition()
self._pending: Optional[tuple[int, int, int, int, bytes]] = None
self._pending: Optional[bytes] = None
self._stop = False
self._started = False
self._thread: Optional[threading.Thread] = None
@@ -110,15 +110,26 @@ class FramePipeWriter:
) -> None:
"""Queue the latest frame without blocking; drop any stale queued frame."""
data = bytes(payload)
header = pack_czfr_header(width, height, pixfmt, flags, len(data))
packet = header + data
with self._cond:
if self._stop:
return
if self._pending is not None:
self._frames_dropped += 1
self._pending = (width, height, pixfmt, flags, data)
self._pending = packet
self._frames_pushed += 1
self._cond.notify()
def _close_fd_locked(self) -> None:
if self._owns_fd and self._fd >= 0:
fd = self._fd
self._fd = -1
try:
os.close(fd)
except OSError:
pass
def stop(self, timeout: float = 1.0) -> None:
with self._cond:
self._stop = True
@@ -128,14 +139,10 @@ class FramePipeWriter:
if thread is not None and thread.is_alive():
thread.join(timeout=timeout)
with self._cond:
if thread is None or not thread.is_alive():
self._thread = None
self._started = False
if self._owns_fd and self._fd >= 0:
try:
os.close(self._fd)
except OSError:
pass
self._fd = -1
self._close_fd_locked()
def _write_packet(self, packet: bytes) -> bool:
mv = memoryview(packet)
@@ -144,12 +151,24 @@ class FramePipeWriter:
try:
while offset < total:
with self._cond:
if self._stop:
if self._stop or self._fd < 0:
return False
fd = self._fd
try:
written = os.write(self._fd, mv[offset:])
written = os.write(fd, mv[offset:])
except BlockingIOError:
select.select([], [self._fd], [], 0.05)
while True:
with self._cond:
if self._stop or self._fd < 0:
return False
fd = self._fd
try:
select.select([], [fd], [], 0.05)
break
except InterruptedError:
continue
except (OSError, ValueError):
return False
continue
except (BrokenPipeError, OSError):
return False
@@ -161,24 +180,29 @@ class FramePipeWriter:
mv.release()
def _writer_loop(self) -> None:
try:
while True:
with self._cond:
while self._pending is None and not self._stop:
self._cond.wait()
if self._stop:
return
frame = self._pending
packet = self._pending
self._pending = None
assert frame is not None
width, height, pixfmt, flags, payload = frame
header = pack_czfr_header(width, height, pixfmt, flags, len(payload))
if not self._write_packet(header + payload):
assert packet is not None
if not self._write_packet(packet):
with self._cond:
self._stop = True
return
with self._cond:
self._frames_written += 1
finally:
with self._cond:
self._started = False
self._thread = None
if self._stop:
self._close_fd_locked()
class JsonProtocolServer:
@@ -338,10 +362,10 @@ class JsonProtocolServer:
buf.extend(chunk)
def run(self) -> int:
self._worker.start()
stdin_fd = self._get_stdin_fd() if self._wakeup_fd is not None else None
fd_buf = bytearray()
try:
self._worker.start()
while not self._shutdown_requested:
if stdin_fd is not None and self._wakeup_fd is not None:
raw_line = self._read_line_fd(stdin_fd, self._wakeup_fd, fd_buf)

View File

@@ -95,6 +95,7 @@ class FakePicamera2:
self.pre_callback = None
self.recording = False
self.recording_attempts = []
self.recording_argv_history = []
self.captured_files = []
self.direct_captures = []
self.switched_captures = []
@@ -170,8 +171,11 @@ class FakePicamera2:
self.encoder = encoder
self.output = output
self.recording = True
# Extract real path from output_filename string (after -f mp4 -movflags +faststart )
path = output.output_filename.split()[-1].strip("'\"")
# Match upstream picamera2 FfmpegOutput.start(), which splits
# output_filename via plain str.split() without stripping shell quotes.
tokens = output.output_filename.split()
self.recording_argv_history.append(list(tokens))
path = tokens[-1]
with open(path, "wb") as f:
f.write(b"\x00\x00\x00\x18ftypmp42MOCKMP4")
@@ -591,6 +595,53 @@ class Picam2WorkerTest(unittest.TestCase):
self.assertEqual(payload[y_len : y_len + uv_len], b"\x80" * uv_len)
self.assertEqual(payload[y_len + uv_len :], b"\x81" * uv_len)
def test_start_video_preserves_spaces_and_special_chars_in_path(self):
worker, _, _ = self._make_worker()
worker.start()
worker.configure(
mode="video",
main_w=1280,
main_h=720,
preview_w=226,
preview_h=128,
fps=30,
zoom=1.0,
ev=0.0,
transform="0",
)
picam = FakePicamera2.instances[-1]
with tempfile.TemporaryDirectory() as tmpdir:
spaced_dir = os.path.join(tmpdir, "My Drive (1);test's")
os.makedirs(spaced_dir, exist_ok=True)
video_path = os.path.join(spaced_dir, ".VID_20261119_124000.mp4.part")
res = worker.start_video(
tmp_path=video_path,
width=1280,
height=720,
fps=30,
bitrate=4000000,
audio=False,
)
self.assertFalse(res["audio_recorded"])
self.assertTrue(picam.recording)
self.assertTrue(os.path.isfile(video_path))
self.assertEqual(
picam.recording_argv_history[-1],
["-f", "mp4", "-movflags", "+faststart", video_path],
)
self.assertIsInstance(picam.output.output_filename, str)
self.assertIn("-f mp4", picam.output.output_filename)
self.assertIn("-movflags +faststart", picam.output.output_filename)
self.assertIn(video_path, picam.output.output_filename)
self.assertEqual(
str(picam.output.output_filename),
f"-f mp4 -movflags +faststart {video_path}",
)
stop_res = worker.stop_video()
self.assertGreater(stop_res["bytes"], 0)
if __name__ == "__main__":
unittest.main()

View File

@@ -1,3 +1,4 @@
import io
import json
import os
import select
@@ -8,6 +9,7 @@ import tempfile
import threading
import time
import unittest
from unittest import mock
from czcamera_cam.protocol import (
CZFR_HEADER_STRUCT,
@@ -16,6 +18,7 @@ from czcamera_cam.protocol import (
PIXFMT_RGB24,
PIXFMT_YUV420,
FramePipeWriter,
JsonProtocolServer,
pack_czfr_header,
)
@@ -394,6 +397,120 @@ class ProtocolTest(unittest.TestCase):
if proc.stderr:
proc.stderr.close()
def test_frame_pipe_writer_validates_header_in_push_frame(self):
r_fd, w_fd = os.pipe()
thread_errors = []
orig_hook = threading.excepthook
threading.excepthook = lambda args: thread_errors.append(args)
writer = FramePipeWriter(w_fd, owns_fd=False)
writer.start()
try:
with self.assertRaises(ValueError):
writer.push_frame(226, 170, 99, 0, b"\x00")
with self.assertRaises(ValueError):
writer.push_frame(70000, 170, PIXFMT_YUV420, 0, b"\x00")
self.assertEqual(thread_errors, [])
finally:
writer.stop()
threading.excepthook = orig_hook
os.close(r_fd)
os.close(w_fd)
def test_frame_pipe_writer_select_errors_and_safe_close(self):
# 1. InterruptedError retries select, then OSError / ValueError exit cleanly without thread crash
for terminal_exc in (OSError("EBADF"), ValueError("fd out of range")):
r_fd, w_fd = os.pipe()
thread_errors = []
orig_hook = threading.excepthook
threading.excepthook = lambda args: thread_errors.append(args)
writer = FramePipeWriter(w_fd, owns_fd=False)
select_calls = []
def fake_select(_r, wlist, _x, _timeout):
select_calls.append(len(select_calls))
if len(select_calls) == 1:
raise InterruptedError("EINTR")
raise terminal_exc
try:
with mock.patch("czcamera_cam.protocol.os.write", side_effect=BlockingIOError), \
mock.patch("czcamera_cam.protocol.select.select", side_effect=fake_select):
writer.start()
writer.push_frame(4, 4, PIXFMT_YUV420, 0, b"\x00" * 24)
deadline = time.monotonic() + 2.0
while len(select_calls) < 2 and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.05)
self.assertEqual(len(select_calls), 2)
self.assertEqual(thread_errors, [])
finally:
writer.stop()
threading.excepthook = orig_hook
os.close(r_fd)
os.close(w_fd)
# 2. owns_fd=True must NOT close fd while writer thread is still alive on stop() timeout
r_fd, w_fd = os.pipe()
writer = FramePipeWriter(w_fd, owns_fd=True)
write_started = threading.Event()
release_write = threading.Event()
closed_fds = []
real_close = os.close
def slow_write(_fd, buf):
write_started.set()
release_write.wait(timeout=2.0)
return len(buf)
def tracked_close(fd):
closed_fds.append(fd)
return real_close(fd)
try:
with mock.patch("czcamera_cam.protocol.os.write", side_effect=slow_write), \
mock.patch("czcamera_cam.protocol.os.close", side_effect=tracked_close):
writer.start()
writer.push_frame(4, 4, PIXFMT_YUV420, 0, b"\x00" * 24)
self.assertTrue(write_started.wait(timeout=2.0))
# Timeout expires while slow_write is still blocked; fd must NOT be closed yet.
writer.stop(timeout=0.02)
self.assertNotIn(w_fd, closed_fds)
# Unblock writer thread; thread finishes and closes w_fd exactly once.
release_write.set()
deadline = time.monotonic() + 2.0
while w_fd not in closed_fds and time.monotonic() < deadline:
time.sleep(0.01)
self.assertEqual(closed_fds.count(w_fd), 1)
writer.stop(timeout=0.1)
self.assertEqual(closed_fds.count(w_fd), 1)
finally:
release_write.set()
real_close(r_fd)
if w_fd not in closed_fds:
real_close(w_fd)
def test_json_protocol_server_calls_shutdown_if_worker_start_raises(self):
events = []
class FailingStartWorker:
def start(self):
events.append("start")
raise RuntimeError("camera open failed")
def shutdown(self):
events.append("shutdown")
server = JsonProtocolServer(
worker_factory=lambda _emit: FailingStartWorker(),
stdin=io.StringIO(""),
stdout=io.StringIO(""),
)
with self.assertRaisesRegex(RuntimeError, "camera open failed"):
server.run()
self.assertEqual(events, ["start", "shutdown"])
if __name__ == "__main__":
unittest.main()