docs: add README, guides, and Apache 2.0 license

This commit is contained in:
2026-11-19 18:50:30 -05:00
parent e3bd5bf615
commit d0c0ac1029
5 changed files with 792 additions and 0 deletions

201
LICENSE.md Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the NOTICE text file within such
distribution, excluding those notices that do not pertain to any
part of the Derivative Works, in at least one of the following
places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation,
if provided along with the Derivative Works; or, within a
display generated by the Derivative Works, if and wherever such
third-party notices normally appear. The contents of the NOTICE
text file are for informational purposes only and do not modify
the License. You may add Your own attribution notices within
Derivative Works that You distribute, alongside or as an
addendum to the NOTICE text file from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the copyright notice of the Work.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, but not limited to, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate action) or
agreed to in writing, shall any Contributor be liable to You for
damages, including any direct, indirect, special, incidental, or
consequential damages of any kind arising out of this License or out
of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or
malfunction, or any and all other commercial damages or losses), even
if such Contributor has been advised of the possibility of such
damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 cottongin
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

121
README.md Normal file
View File

@@ -0,0 +1,121 @@
> [!IMPORTANT]
> This project was developed with AI coding assistance and has not yet undergone a full hardware soak test on physical CM0 hardware. It is provided under the Apache 2.0 license and may require adjustment for other environments.
# `czcamera` — CardputerZero Camera App
A dedicated `320×170` camera, video, timelapse, and gallery application built for the **M5Stack CardputerZero** (Raspberry Pi CM0, ARM64 Debian Bookworm, non-touch `/dev/fb0`, 46-key `cp0-keys`, 8MP Sony IMX219 CSI-2 sensor, ES8389 MEMS microphone & speaker), styled with `shadcn/ui` Zinc Dark and Light themes.
Includes a desktop **SDL2 simulator** (`--sim`) with a procedural test scene (`--mock-cam`) and headless PPM snapshot runner (`--render-test`) for macOS and Linux development.
---
## Key Features
- **Option A Split Layout (`320×170`):** Live `226×170` viewfinder alongside a focusable `94×170` control rail (`1P · 2V · 3T`), with live **`[W]`** rail-side toggle (`right` default or `left`) and **`[T]`** Zinc Dark / Light theme toggle.
- **Photo Mode + 9 Filters:** True ISP `ScalerCrop` zoom (`1x`–`4x` via `5`/`7`), independent `2x` viewfinder-only **Loupe** (`L`), EV (`-2.0` to `+2.0`), `8MP` / `2MP` presets (`R`), `Off`/`3s`/`10s` self-timer (`C`), `[G]` rule-of-thirds grid, and 9 shared RGB24/`libjpeg` filters (`None` zero-re-encode passthrough, `B&W`, `Hi-Con`, `Sepia`, `Cool`, `Vivid`, `Invert`, `Retro`, and Bayer-dithered `GameBoy` DMG).
- **Hardware H.264 Video Mode:** `720p30` (default), `1080p30`, and `480p30` `.mp4` recording with ES8389 MEMS mic ON by default (`[M]` idle mute toggle, graceful muted fallback on `audio_unavailable`), live 16:9 letterboxed viewfinder, and live digital zoom during capture.
- **Foreground Timelapse Mode:** `2MP` default (`1080p` / `8MP` presets), customizable interval/FPS/stop presets (`C` / `P`), output to `TL_<timestamp>/` JPEGs or compiled `TL_<timestamp>.mp4` (`h264_v4l2m2m` with automatic `libx264` fallback and `8MP`→`1440×1080` scaling for VideoCore IV's `2048px` encoder ceiling), sysfs backlight auto-dim + **dimmed safe-wake** (any keypress only wakes the display), and startup recovery for orphaned `.tl_work_*` sessions.
- **Full-Screen Gallery & Video Playback (`[8]`):** Pauses the camera backend while open, supports `TL_*` session drill-down, plays `.mp4` videos (with or without audio tracks) via `ffmpeg`/`aplay` (or SDL2 audio on desktop) with `-5s`/`+5s` seek, and enforces `[Y/N]` delete confirmation.
- **Settings & Directory Tree Picker (`[S]`):** Output folder browser (plus `[T]` manual path entry), `Camera Orient` (`auto`, `0°`, `180°`, `H-Flip`, `V-Flip` via ISP `Transform`), rail side, theme, grid, and auto-dim timeout.
- **Sync-Safe & Hardware-Decoupled:** Writes exclusively to `.`-prefixed staging paths until finalized via `fsync` + atomic `rename()` (with a `100 MB` free-space guard), keeping zero runtime/packaging dependencies on external sync tools or direct `libcamera.so` linkage.
---
## Architecture Overview
| Component | Path | Target / Role | Purpose |
|---|---|---|---|
| **C++17 UI & Core** | [`app/`](app/) | CardputerZero (`/dev/fb0` + `cp0-keys`) & macOS (`--sim`) | `czcamera` binary & `czcamera_core` library (`ShadcnCanvas`, `UiController`, filters/JPEG, timelapse engine, gallery model, `VideoPlayer`, and 5 CTest suites). |
| **Python Camera Worker** | [`cam-helper/`](cam-helper/) | CardputerZero (`czcamera-cam`) & `--mock-driver` | Dual-stream (`main` + `lores`) `python3-picamera2` worker driven by newline JSON v1 + 16-byte `CZFR` binary frame pipe. |
| **ARM64 Packaging** | [`packaging/`](packaging/) | ARM64 Docker (`bookworm-slim`) / Debian | Builds `czcamera_1.0.0_m5stack1_arm64.deb` installing `czcamera`, `czcamera-cam`, `czcamera_cam`, and the `APPLaunch` entry/icon. |
---
## Quick Start
### 1. Build & Install on CardputerZero (Docker on macOS/Linux → CM0)
Ensure Docker Desktop is running with `linux/arm64` support, then build `packaging/dist/czcamera_1.0.0_m5stack1_arm64.deb`:
```bash
./packaging/build-deb.sh
scp packaging/dist/czcamera_1.0.0_m5stack1_arm64.deb pi@<cardputerzero-host>:/tmp/
```
Install on the CardputerZero:
```bash
sudo dpkg -i /tmp/czcamera_1.0.0_m5stack1_arm64.deb
sudo apt-get install -f
```
Launch **czcamera** from the `APPLaunch` app grid or run `/usr/bin/czcamera` directly.
### 2. Run the Desktop Simulator (macOS / Linux)
```bash
cmake -S app -B app/build -DCZ_BUILD_APP=ON -DCZ_BUILD_TESTS=ON
cmake --build app/build
./app/build/czcamera --sim --scale 3
```
Run the unit test suites anytime:
```bash
ctest --test-dir app/build --output-on-failure
PYTHONPATH=cam-helper python3 -W error -m unittest discover -s cam-helper/tests -v
python3 -m unittest discover -s packaging/tests -v
```
---
## Core Keyboard Shortcuts (`320×170`)
| Key | Where | Action |
|---|---|---|
| `1`, `2`, `3` | Main View | Switch between **Photo**, **Video**, and **Timelapse** |
| `Enter`, `Space`, `6` | Main View | Trigger shutter / Start-Stop recording / Open Timelapse stop prompt |
| `Up`/`Down` or `k`/`j` | Rail / Lists / Modals | Move selection cursor |
| `Left`/`Right` or `h`/`l` | Rail / Settings | Cycle selected card value (`l` toggles `2x` Loupe in idle Photo view) |
| `5` / `7` | Photo / Video | Step ISP digital crop zoom (`1.0x`–`4.0x`) |
| `L` | Photo | Toggle `2x` viewfinder-only Loupe |
| `F` | Photo | Cycle 9 photo filters (`None` .. `GameBoy`) |
| `R` | Photo / Video / TL (or Offline) | Cycle resolution preset (or recover camera when `Offline`) |
| `C` | Photo / Timelapse | Cycle self-timer (`Off`/`3s`/`10s`) in Photo; open Custom TL modal in Timelapse |
| `M` | Video (idle) / Gallery video | Toggle ES8389 mic audio / Toggle playback mute |
| `G` | Main View | Toggle rule-of-thirds viewfinder grid |
| `W` | Main View | Swap control rail side (`right` ↔ `left`) |
| `T` | Main View / Gallery / DirPicker | Toggle Zinc Dark / Light theme (or type path inside DirPicker) |
| `8` | Main View | Pause camera and open full-screen **Gallery** |
| `S` | Main View | Open **Settings** modal |
| `Esc` / `Q` | Dimmed Timelapse / Modals / Main | Wake dimmed screen safely (first key), cancel/close modal, or exit to `APPLaunch` |
---
## Documentation
- **[Building & Installation Guide](docs/building-and-installation.md)** — Host & device dependencies, `.deb` packaging (`./packaging/build-deb.sh` modes), `APPLaunch` integration, font bundling, SDL2 simulator builds, and C++/Python/packaging tests.
- **[Usage, Controls & Configuration Guide](docs/usage-and-controls.md)** — Capture modes, all 9 photo filters, Timelapse auto-dim safe-wake & recovery, Gallery playback, complete keymap, `config.json` (18 fields), CLI flags, sync-safe staging rules, and troubleshooting.
- **[Architecture & Camera Protocol Reference](docs/architecture-and-protocol.md)** — `cz::ICameraBackend` decoupling boundary, JSON v1 + 16-byte `CZFR` binary frame pipe spec, dual `main`+`lores` camera pipeline, VideoCore IV limits, `320×170` Zinc tokens, and directory map.
- **[Design Specification](docs/superpowers/specs/2026-11-19-czcamera-design.md)** — Original hardware/UI design specification.
- **[Implementation Plan](docs/superpowers/plans/2026-11-19-czcamera.md)** — 7-task TDD architecture and verification plan.
---
## Repository Layout
```text
.
├── app/ # C++17 320x170 UI, filters, timelapse/gallery/playback & 5 CTest suites
├── cam-helper/ # Python 3 czcamera-cam helper (picamera2 + mock driver) & tests
├── packaging/ # ARM64 Docker/.deb builder, APPLaunch desktop/icon & packaging tests
├── docs/ # User/developer guides, design specification & implementation plan
├── chat-summaries/ # Technical implementation summaries
└── LICENSE.md # Apache License 2.0
```
---
## License
Licensed under the **Apache License, Version 2.0**. See [LICENSE.md](LICENSE.md) for the full license text.

View File

@@ -0,0 +1,128 @@
> [!IMPORTANT]
> This project was developed with AI coding assistance and has not yet undergone a full hardware soak test on physical CM0 hardware. It is provided under the Apache 2.0 license and may require adjustment for other environments.
# Architecture & Camera Protocol Reference
`czcamera` separates user-space UI, image processing, media assembly, and storage management in C++17 from Raspberry Pi hardware capture in Python 3 (`python3-picamera2`) through an explicit backend abstraction (`cz::ICameraBackend`).
---
## 1. System Topology & Decoupling Boundary
```text
+-------------------------------------------------------------------+
| C++17 /usr/bin/czcamera |
| - AppView (320x170 ShadcnCanvas: FreeType2 + 5x7 fallback) |
| - UiController, TimelapseEngine, GalleryStore, VideoPlayer |
| - Filters RGB24 + libjpeg still pipeline, BacklightController |
| - Linux (/dev/fb0 + cp0-keys evdev) OR Desktop SDL2 (--sim) |
| | |
| cz::ICameraBackend |
| +---------------+---------------+ |
| | | |
| SubprocessCameraBackend SimCameraBackend |
| (device / --mock-driver) (--sim / --mock-cam / tests) |
+--------------|----------------------------------------------------+
| stdin/stdout JSON v1 + dedicated CZFR fd pipe
v
+-------------------------------------------------------------------+
| Python 3 /usr/bin/czcamera-cam (czcamera_cam) |
| - JsonProtocolServer + FramePipeWriter (latest-slot drop-oldest) |
| - Picam2Worker (main + lores YUV420 dual streams, H264Encoder) |
| - MockCameraDriver (--mock-driver deterministic test driver) |
+-------------------------------------------------------------------+
| python3-picamera2 / libcamera IPA (rpi/vc4)
v
Sony IMX219 (3280x2464) + ES8389 MEMS Mic (ALSA default)
```
### Replacing `picamera2` with Native `libcamera` Later
`czcamera` C++ sources have **zero** `#include <libcamera/...>` or CMake linkage to `libcamera.so`. To swap `python3-picamera2` for a native C++ `libcamera` backend (or `rpicam-apps`), implement [`app/src/camera_backend.hpp`](../app/src/camera_backend.hpp) (`cz::ICameraBackend`) and return it from `create_camera_backend()` in [`app/src/sim_backend.cpp`](../app/src/sim_backend.cpp) without touching `UiController`, `AppView`, filters, timelapse, or gallery code.
---
## 2. Camera Helper Wire Protocol v1
`SubprocessCameraBackend` launches `/usr/bin/czcamera-cam --frame-fd <N>` (overridable via `CZCAMERA_CAM_BIN`, passing `--mock-driver` in protocol tests) with an inherited read/write pipe (`frame_fd`).
### Control Channel (`stdin` / `stdout` Newline-Delimited JSON)
Requests from C++ → Python carry `"id"` (uint64) and `"cmd"`:
| Command | Payload Fields | Reply Extra Fields (`{"id", "ok": true, ...}`) |
|---|---|---|
| `configure` | `mode` (`"photo"`/`"video"`/`"timelapse"`), `main_w`, `main_h`, `preview_w` (`226`), `preview_h` (`170`), `fps`, `zoom`, `ev`, `transform` (`"auto"`/`"0"`/`"180"`/`"hflip"`/`"vflip"`) | `mode`, `main_w`, `main_h`, `preview_w`, `preview_h` (`226x128` for 16:9 modes), `transform`, `is_16_9` |
| `set_controls` | Optional `zoom` (`1.0..4.0`), `ev` (`-2.0..+2.0`) | `zoom`, `ev` |
| `capture_still` | `tmp_path`, `width`, `height` | `bytes` (temporarily stops video / switches to still format if needed and restores stream config) |
| `start_video` | `tmp_path`, `width`, `height`, `fps`, `bitrate`, `audio` (`bool`) | `audio_recorded` (`bool`) |
| `stop_video` | — | `duration_sec`, `bytes`, `audio_recorded` |
| `pause` | — | Stops recording if active, closes camera & releases IMX219 lock |
| `resume` | — | Re-opens camera and restores last `configure` spec |
| `shutdown` | — | Tears down writer & camera cleanly and exits `0` |
Asynchronous Events from Python → C++ (no `"id"`):
- `{"event": "ready", "protocol": 1, "backend": "picamera2"|"mock", "sensor": "...", "has_audio": true|false}`
- `{"event": "warn", "code": "...", "message": "..."}` (for example `"audio_unavailable"`, `"invalid_json"`, `"control_error"`)
- `{"event": "error", "code": "...", "message": "..."}`
### Binary Preview Frame Channel (`--frame-fd <N>`, 16-Byte `CZFR` Header)
Every preview frame packet starts with a fixed **16-byte little-endian** header (`struct.Struct("<4sHHBBHI")`) followed immediately by `payload_len` bytes:
| Offset | Size | C Type | Field | Description |
|---|---|---|---|---|
| `0` | `4` | `char[4]` | `magic` | `"CZFR"` (`0x43 0x5A 0x46 0x52`) |
| `4` | `2` | `uint16_t` | `width` | Negotiated preview frame width (e.g., `226`) |
| `6` | `2` | `uint16_t` | `height` | Preview frame height (`170` for 4:3, `128` for 16:9) |
| `8` | `1` | `uint8_t` | `pixfmt` | `1` = `YUV420`, `2` = `RGB24` |
| `9` | `1` | `uint8_t` | `flags` | Bit `0` (`0x01`): `FLAG_ASPECT_16_9` |
| `10` | `2` | `uint16_t` | `reserved` | Always `0` |
| `12` | `4` | `uint32_t` | `payload_len` | `width * height * 3 / 2` (`YUV420`) or `width * height * 3` (`RGB24`) |
**Backpressure Contract (Review Focus #1):**
- `FramePipeWriter` uses a single-slot bounded queue (`_pending`). When the UI consumer slows down, `push_frame()` drops any unconsumed queued packet and replaces it with the newest frame, keeping camera/H.264 encoder threads non-blocking.
- `Picam2Worker._extract_lores_yuv420()` inspects the negotiated `lores` `stride` (handling 64-byte DMA padding such as `256` for `226px`) and strips row padding before packing tight `YUV420` payloads.
---
## 3. Target Hardware Constraints & Media Pipelines
- **Sony IMX219 Sensor Modes:** `640×480` (4:3, crop `(1000,752)/1280×960`), `1640×1232` (4:3 full-FOV 2×2 binned), `1920×1080` (16:9 crop), `3280×2464` (4:3 8MP full sensor).
- **Video Output (`FfmpegOutput`):** `_FfmpegOutputTarget` overrides `.split()` cleanly around `picamera2.outputs.FfmpegOutput`'s whitespace `.split()` so staging paths containing spaces or special characters (and ending in `.mp4.part`, with `-f mp4 -movflags +faststart`) remain exact `argv` tokens.
- **Timelapse Compilation:** [`TimelapseEngine`](../app/src/timelapse_engine.hpp) invokes `ffmpeg` with `-vf scale=1440:1080:flags=lanczos` for `8MP` sessions to stay under VideoCore IV's `2048px` H.264 limit, tries `h264_v4l2m2m` (`6M`, `yuv420p`), and retries automatically with `libx264 -preset veryfast -crf 22 -pix_fmt yuv420p` on failure.
- **Gallery Playback:** [`VideoPlayer`](../app/src/video_player.hpp) probes duration & audio presence via `ffprobe`, spawns `ffmpeg` raw `rgb24` frames timed cleanly to PTS, and drives audio through ALSA `aplay` on Linux or `set_pcm_sink` (SDL2 audio queue) on desktop—allowing silent `.mp4` files (compiled timelapses or muted clips) to play smoothly without audio failure.
---
## 4. `320×170` UI Renderer & Zinc Color Tokens
[`AppView`](../app/src/app_ui.hpp) renders into an offscreen `320×170` ARGB8888 canvas with SDF antialiased rounded primitives and FreeType2 + `5×7` bitmap fallback, then blits via [`fb_blit.hpp`](../app/src/fb_blit.hpp) (`RGB565` / `RGB24` / `XRGB8888`) or SDL2 texture.
Exact palette tokens defined in [`app/src/theme.cpp`](../app/src/theme.cpp):
| Token | Zinc Dark (`ThemeMode::Dark`) | Zinc Light (`ThemeMode::Light`) |
|---|---|---|
| `background` / `card` | `#09090b` / `#09090b` | `#fafafa` / `#ffffff` |
| `muted` | `#18181b` | `#f4f4f5` |
| `border` | `#27272a` | `#e4e4e7` |
| `ring` | `#d4d4d8` | `#71717a` |
| `foreground` / `muted_foreground` | `#fafafa` / `#a1a1aa` | `#09090b` / `#71717a` |
| `active_tab` / `active_tab_foreground` | `#27272a` / `#fafafa` | `#ffffff` / `#09090b` |
| `status_online` / `status_online_bg` | `#4ade80` / `#11261a` | `#16a34a` / `#dcfce7` |
| `status_sleeping` / `status_sleeping_bg` | `#fbbf24` / `#271d0b` | `#d97706` / `#fef3c7` |
| `status_error` / `status_error_bg` | `#f87171` / `#2b1214` | `#dc2626` / `#fee2e2` |
| `viewfinder_surround` | `#050507` | `#050507` |
---
## 5. Source Directory Map
- **`app/src/`**:
- `theme.{hpp,cpp}`, `fb_blit.hpp`, `config.{hpp,cpp}`, `storage.{hpp,cpp}`
- `filters.{hpp,cpp}`, `jpeg_pipeline.{hpp,cpp}`
- `camera_backend.hpp`, `subprocess_backend.{hpp,cpp}`, `sim_backend.{hpp,cpp}`
- `backlight.{hpp,cpp}`, `timelapse_engine.{hpp,cpp}`, `gallery_model.{hpp,cpp}`, `video_player.{hpp,cpp}`
- `ui_controller.{hpp,cpp}`, `app_ui.{hpp,cpp}`, `evdev_repeat_guard.hpp`, `main.cpp`
- **`app/tests/`**: `test_config_and_storage.cpp`, `test_filters_and_jpeg.cpp`, `test_backend_protocol.cpp`, `test_timelapse_and_gallery.cpp`, `test_ui_controller.cpp`
- **`cam-helper/`**: `bin/czcamera-cam`, `czcamera_cam/{__init__,protocol,picam2_worker}.py`, `tests/test_{protocol,picam2_worker}.py`
- **`packaging/`**: `Dockerfile.arm64`, `build-deb.sh`, `czcamera.desktop`, `czcamera.png`, `debian/{control,postinst,prerm}`, `tests/test_packaging.py`

View File

@@ -0,0 +1,188 @@
> [!IMPORTANT]
> This project was developed with AI coding assistance and has not yet undergone a full hardware soak test on physical CM0 hardware. It is provided under the Apache 2.0 license and may require adjustment for other environments.
# Building & Installation Guide
This guide covers building the CardputerZero ARM64 `.deb` package, installing on device with `APPLaunch` integration, building the macOS/Linux SDL2 desktop simulator, and running all verification suites.
---
## 1. Prerequisites
### CardputerZero Device (Runtime)
- Raspberry Pi CM0 (ARM64 Debian Bookworm, `dtoverlay=imx219` enabled in `/boot/firmware/config.txt`)
- Sony IMX219 camera module verified with `rpicam-hello --list-cameras`
- `APPLaunch` application launcher and `/dev/fb0` + `cp0-keys` `evdev` input device
- Runtime `.deb` dependencies (declared in [`packaging/debian/control`](../packaging/debian/control)):
- `python3 (>= 3.9)`
- `python3-picamera2`
- `ffmpeg`
- `alsa-utils` (`aplay`)
- `libjpeg62-turbo | libjpeg8`
- `libfreetype6`
- `libc6`, `libstdc++6`
> Note: `czcamera` intentionally has **no** dependency on `cp0-sync` and **no** direct C++ linkage to `libcamera0*` or `libcamera.so`.
### Docker Cross-Build Host (macOS / Linux)
- Docker Desktop (or Docker Engine with `linux/arm64` emulation / `buildx`)
### Desktop Simulator Build (macOS / Linux)
- CMake `>= 3.16` and a C++17 compiler (`clang++` or `g++`)
- `pkg-config`
- `libjpeg` (`libjpeg-turbo` via Homebrew `jpeg-turbo`/`libjpeg` or Debian `libjpeg62-turbo-dev`)
- `SDL2` (`sdl2` via Homebrew or `libsdl2-dev`)
- **Optional:** `FreeType2` (`freetype` / `libfreetype-dev`) for crisp antialiased UI fonts (falls back automatically to the built-in `5×7` bitmap renderer if absent)
- **Optional:** `ffmpeg` & `ffprobe` on `PATH` for desktop Timelapse MP4 compilation and Gallery `.mp4` playback tests
- Python `>= 3.9` for running helper/packaging test suites
---
## 2. Building the ARM64 Debian Package (`.deb`)
Use [`packaging/build-deb.sh`](../packaging/build-deb.sh) in one of four supported modes:
```bash
./packaging/build-deb.sh --help
```
### Option A: Docker `linux/arm64` Build (Recommended on macOS / x86_64)
Builds a clean `debian:bookworm-slim` (`linux/arm64`) container via [`packaging/Dockerfile.arm64`](../packaging/Dockerfile.arm64), compiles `czcamera` with `-DCZ_BUILD_APP=ON -DCZ_TARGET_DEVICE=ON -DCZ_BUILD_TESTS=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS_RELEASE="-O2"`, executes ARM64 `ctest` and `cam-helper/tests`, and outputs `packaging/dist/czcamera_1.0.0_m5stack1_arm64.deb`:
```bash
./packaging/build-deb.sh
```
> Why `-O2` without global `-DNDEBUG`: the ARM64 verification step runs the C++ `ctest` binaries (`app/tests/*.cpp`) built in the same tree, and those tests use `<cassert>` `assert()`.
### Option B: Native Build on CardputerZero / ARM64 Linux
On an ARM64 Debian host with build dependencies installed (`build-essential cmake pkg-config libjpeg62-turbo-dev libfreetype-dev dpkg-dev`):
```bash
./packaging/build-deb.sh --local
```
### Option C: Stage Directory or Supply Prebuilt Binary
Stage the package tree without running `dpkg-deb` or Docker (useful for inspection or custom packaging):
```bash
./packaging/build-deb.sh --stage-only /tmp/czcamera-stage --bin /path/to/czcamera
```
Flags supported by `build-deb.sh`:
| Flag | Description |
|---|---|
| `--local` | Build `app/build-arm64` natively on Linux ARM64 and package `.deb` |
| `--stage-only <dir>` | Stage package files into `<dir>` with target permissions and exit |
| `--bin <path>` / `--ui-bin <path>` | Supply a prebuilt `czcamera` binary (`--ui-bin` is an alias for `--bin`) |
| `--out-dir <dir>` | Output directory for `.deb` (default: `packaging/dist/`) |
| `-h`, `--help` | Show usage help |
### Optional TrueType Font Bundling
If TTF/OTF font files exist under `app/assets/fonts/` or `packaging/fonts/` before running `build-deb.sh`, they are staged into `/usr/share/czcamera/fonts/` (`0644`). At runtime, `cz::AppView` checks `/usr/share/czcamera/fonts/` first, then common system font directories, and falls back to the built-in `5×7` bitmap font cleanly if none are installed.
---
## 3. Installing & Uninstalling on CardputerZero
Copy the generated package to the device and install via `dpkg` + `apt-get`:
```bash
scp packaging/dist/czcamera_1.0.0_m5stack1_arm64.deb pi@<cardputerzero-host>:/tmp/
ssh pi@<cardputerzero-host> 'sudo dpkg -i /tmp/czcamera_1.0.0_m5stack1_arm64.deb && sudo apt-get install -f'
```
### Installed Layout
| Destination Path | Mode | Role |
|---|---|---|
| `/usr/bin/czcamera` | `0755` | C++17 `320×170` `fbdev` + `evdev` camera application binary |
| `/usr/bin/czcamera-cam` | `0755` | Python 3 camera worker launcher (`python3-picamera2`) |
| `/usr/lib/czcamera/czcamera_cam/*.py` | `0644` | Protocol, `FramePipeWriter`, `Picam2Worker`, and mock driver modules |
| `/usr/share/APPLaunch/applications/czcamera.desktop` | `0644` | `APPLaunch` launcher entry (`Name=czcamera`, `Exec=/usr/bin/czcamera`) |
| `/usr/share/APPLaunch/share/images/czcamera.png` | `0644` | `80×80` Zinc dark camera launcher icon |
| `/usr/share/czcamera/fonts/*.ttf` *(optional)* | `0644` | Optional bundled UI fonts |
### Sanity Checks on Device
Verify shared libraries (`libjpeg.so.62` / `libfreetype.so.6` present, zero `libcamera.so` linkage) and camera visibility:
```bash
ldd /usr/bin/czcamera
rpicam-hello --list-cameras
```
Launch **czcamera** from the `APPLaunch` grid, or test from TTY/SSH:
```bash
/usr/bin/czcamera
```
### Uninstalling
```bash
sudo apt-get remove czcamera
```
[`packaging/debian/prerm`](../packaging/debian/prerm) automatically cleans Python `__pycache__` bytecode under `/usr/lib/czcamera` on package removal or deconfiguration.
---
## 4. Building & Running the Desktop SDL2 Simulator
Configure and build on macOS or Linux desktop:
```bash
cmake -S app -B app/build -DCZ_BUILD_APP=ON -DCZ_BUILD_TESTS=ON
cmake --build app/build
```
Run the interactive `320×170` SDL2 simulator (defaults to `SimCameraBackend` when `--sim` or `--mock-cam` is given):
```bash
./app/build/czcamera --sim --scale 3
```
Render headless `P6 320×170` PPM snapshots (`163215` bytes each) for CI or visual inspection:
```bash
./app/build/czcamera --render-test /tmp/cz_photo.ppm --theme dark --mode photo --rail right
./app/build/czcamera --render-test /tmp/cz_light_left.ppm --theme light --mode photo --rail left
./app/build/czcamera --render-test /tmp/cz_video.ppm --theme dark --mode video
./app/build/czcamera --render-test /tmp/cz_timelapse.ppm --theme dark --mode timelapse
./app/build/czcamera --render-test /tmp/cz_gallery.ppm --theme dark --mode gallery
./app/build/czcamera --render-test /tmp/cz_settings.ppm --theme dark --mode settings
```
### CMake Build Options
| Option | Default | Effect |
|---|---|---|
| `CZ_BUILD_APP` | `OFF` | Build the `czcamera` executable in addition to `czcamera_core` |
| `CZ_TARGET_DEVICE` | `OFF` | Build Linux `/dev/fb0` + `cp0-keys` `evdev` backend instead of SDL2 (Linux only) |
| `CZ_BUILD_TESTS` | `ON` | Build the 5 `ctest` suites |
| `CZ_ENABLE_LVGL` | `OFF` | Link optional `lvgl::lvgl` (`CP0_HAS_LVGL=1`) if available |
---
## 5. Running Test Suites
Run all three suites cleanly from the repository root:
```bash
# C++ unit & integration tests (5 suites)
ctest --test-dir app/build --output-on-failure -V
# Python camera helper & mock-driver IPC tests (18 tests, warnings-as-errors)
PYTHONPATH=cam-helper python3 -W error -m unittest discover -s cam-helper/tests -v
# Packaging metadata, icon, maintainer script & staging tests (4 tests)
python3 -m unittest discover -s packaging/tests -v
```
*(Note: `test_backend_protocol` also spawns `cam-helper/bin/czcamera-cam --mock-driver` end-to-end across pipes to validate C++ ↔ Python JSON v1 + `CZFR` binary framing.)*

154
docs/usage-and-controls.md Normal file
View File

@@ -0,0 +1,154 @@
> [!IMPORTANT]
> This project was developed with AI coding assistance and has not yet undergone a full hardware soak test on physical CM0 hardware. It is provided under the Apache 2.0 license and may require adjustment for other environments.
# Usage, Controls & Configuration Guide
`czcamera` is operated entirely with the 46-key CardputerZero keyboard (`cp0-keys`) or an attached keyboard in the SDL2 desktop simulator.
---
## 1. Screen Layout (Option A Split View)
The `320×170` canvas splits into two regions whose horizontal side swaps dynamically with **`W`** (or via Settings → `Control Rail`):
- **Viewfinder (`226×170`):** `16:9` modes (`720p`, `1080p` Video, `1080p` Timelapse) letterbox cleanly into `226×127` centered on a `#050507` surround; `4:3` modes (`8MP`, `2MP`, `480p`) fill `226×170`. Minimal corner badges show active filter, crop zoom / `2x` Loupe state, timer countdown, `● REC MM:SS`, or Timelapse shot counter/next-shot countdown.
- **Control Rail (`94×170`):** Displays `1P · 2V · 3T` mode tabs at the top, 4 setting cards tailored to the active mode, and a compact 2-line `<kbd>` keybind hint footer.
---
## 2. Capture Modes
### Photo Mode (`1`)
- **Resolutions (`R` or card 0):** `8MP` (`3280×2464` JPEG) default, `2MP` (`1640×1232` JPEG).
- **Digital Crop Zoom vs. Viewfinder Loupe:**
- **`5` / `7`**: Steps ISP `ScalerCrop` (`1.0x`, `1.5x`, `2.0x`, `3.0x`, `4.0x`). Both the live preview and captured JPEG are cropped cleanly to that region.
- **`L`** (or `l` on Photo idle view): Toggles a **`2x` Viewfinder-Only Loupe** for checking framing/focus without cropping the saved full-resolution photo.
- **Exposure Value (card 1, `Left`/`Right`):** `-2.0` to `+2.0` in `0.5` EV steps.
- **Photo Filters (`F` or card 2):** Cycles all 9 filters live on the preview and applies them on JPEG save (`None` writes the sensor JPEG directly with zero re-encode):
`None` (`none`), `B&W` (`bw`), `Hi-Con` (`hicon`), `Sepia` (`sepia`), `Cool` (`cool`), `Vivid` (`vivid`), `Invert` (`invert`), `Retro` (`retro`), `GameBoy` (`gameboy`, scaled integer blocks with 4-shade Bayer DMG palette).
- **Self-Timer (`C` or card 3):** Cycles `Off` (`0s`), `3s`, `10s`. Press `Esc` during countdown to cancel without quitting.
- **Shutter (`Enter`, `Space`, `6`):** Stages to `.IMG_<ts>.jpg.tmp`, applies filter if active, `fsync`s, and commits atomically to `IMG_<ts>.jpg` (adding `_01`, `_02`, ... on same-second collisions).
### Video Mode (`2`)
- **Resolutions (`R` or card 0, while idle):** `720p` (`1280×720` @ 30fps, default), `1080p` (`1920×1080` @ 30fps), `480p` (`640×480` @ 30fps).
- **Audio (`M` or card 1, while idle):** ES8389 MEMS microphone ON by default (`audio=true`). If ALSA capture is unavailable or busy at recording start, `czcamera-cam` emits `audio_unavailable`, shows a warning toast, and falls back to muted `.mp4` recording instead of aborting.
- **Live Zoom (`5` / `7` or card 2):** Active both before and during recording (`1.0x`–`4.0x`).
- **Storage Indicator (card 3):** Displays read-only `FREE` space remaining on the target mount (`100 MB` minimum enforced every 2 seconds while recording; auto-stops safely if space drops below `100 MB`).
- **Recording Lock:** While `● REC` is active, mode switches (`1`/`2`/`3`), `[8]` Gallery, `[S]` Settings, `[W]` rail flip, `[T]` theme toggle, `[M]`/`[R]`, and `Q` are locked out. Press `Enter`, `Space`, `6`, or `Esc` to stop recording cleanly.
### Timelapse Mode (`3`)
- **Defaults & Presets:**
- **Resolution (`R` or card 2):** `2MP` (`1640×1232` default for tighter intervals), `1080p` (`1920×1080`), `8MP` (`3280×2464`).
- **Interval (card 0):** Cycles `2s`, `5s` (default), `10s`, `30s`, `60s`, `300s` (or any custom `1..3600s` via `[C]` / `[P]`).
- **Output Mode (card 1):** `video` (`TL_<ts>.mp4`, default) or `photos` (`TL_<ts>/frame_0001.jpg`...).
- **Stop Condition (card 3):** `Manual` (default), `60 shots`, `120 shots`, `300 shots`, `15 min`, `30 min`, `60 min` (or custom via `[C]` / `[P]`).
- **Custom Input Modal (`C` or `P` while idle):** Adjusts exact Interval (`1..3600s`), FPS (`15`, `24`, `30`), Stop Mode (`manual` / `shots` / `duration`), and Stop Value (`1..9999` shots or `1..1440` min) with numeric digits or `Left`/`Right`. `Enter` saves and closes; `Esc` discards.
- **MP4 Compilation & VideoCore IV Compliance:**
- Frames stage inside `.tl_work_<ts>/` with a `manifest.json` heartbeat.
- On stop/completion in `video` mode, `ffmpeg` prefers hardware `h264_v4l2m2m` (`6M`, `yuv420p`) and automatically falls back to `libx264 -preset veryfast -crf 22 -pix_fmt yuv420p` if hardware encoding fails.
- Because Raspberry Pi VideoCore IV's hardware H.264 encoder caps dimensions at `2048px`, **`8MP` (`3280×2464`) frames automatically scale to `1440×1080` (`lanczos`)** during MP4 compile (while individual `Photos`-mode frames remain full `8MP`).
- Press `Esc` during `TimelapseCompiling` to cancel compilation cleanly and preserve the raw frames in a non-hidden `TL_<ts>/` folder.
- **Auto-Dim & Safe Wake:**
- When capturing, the screen dims after `timelapse_dim_sec` idle seconds (`15s` default; configurable `15s`/`30s`/`60s`/`Off` in Settings) via `/sys/class/backlight/*/brightness` (or a software black frame fallback on desktop/headless).
- **Safe-Wake Rule:** Pressing **any** key while dimmed (including `Enter`, `6`, `Esc`, `Q`) **only wakes the display** and resets the idle timer — and on Linux `evdev`, held auto-repeats (`ev.value == 2`) for that wake key are suppressed until key release (`ev.value == 0`). Press `Esc`, `Enter`, `6`, or `Q` while **awake** to open `TimelapseStopConfirm` (`[Y]` stop & finish/compile, `[N]`/`[Esc]` keep capturing).
- **Crash Recovery on Launch:** On startup, `czcamera` scans `output_dir` for incomplete `.tl_work_*` directories containing valid JPEGs and prompts `TimelapseRecovery`: `[C]` Compile to MP4, `[K]` Keep Photos, `[D]` Discard, or `[Esc]` Defer.
---
## 3. Gallery & Media Playback (`8`)
Pressing `8` pauses the camera backend (`pause` IPC, releasing the sensor) and opens the full-screen `320×170` Gallery showing items from `output_dir` (newest first, ignoring all `.`-prefixed hidden files/directories):
| Key | Gallery Context | Action |
|---|---|---|
| `Up`/`Down`/`Left`/`Right` or `k`/`j`/`h`/`l` | Photo / Video (stopped) / TL Folder | Navigate items |
| `Space` / `Enter` | `TL_*` Timelapse Folder | Drill into folder (`Backspace` or `Esc` returns to root) |
| `Space` / `Enter` | Video (`.mp4`) | Play / Pause |
| `Left` / `Right` or `h` / `l` | Video (playing) | Seek `-5s` / `+5s` |
| `M` | Video selected | Toggle playback mute (works cleanly even on silent `.mp4` files with no audio stream) |
| `D` / `Delete` | Any item | Open `[Y]` Confirm / `[N]`/`Esc` Cancel delete prompt |
| `T` | Gallery | Toggle Zinc Dark / Light theme |
| `1`, `2`, `3` | Gallery | Close Gallery, resume camera, and jump directly to mode |
| `Esc` / `Q` | Gallery root | Close Gallery and resume camera live preview |
---
## 4. Settings Modal & Directory Tree Picker (`S`)
| Row | Setting | Values / Action |
|---|---|---|
| 0 | `Output Dir` | Opens `DirPicker` (`Enter` drill down, `Backspace` parent, `Space` select highlighted dir, `.` select current dir, `/` root, `~` home, `[T]` manual `TextInput` with printable ASCII + spaces, `Esc` back) |
| 1 | `Control Rail` | `right` (default) / `left` |
| 2 | `Theme` | `dark` (Zinc Dark) / `light` (Zinc Light) |
| 3 | `Grid Overlay` | `on` (`true`) / `off` (`false`) |
| 4 | `Timelapse Dim` | `15s` / `30s` / `60s` / `Off` (`0`) |
| 5 | `Camera Orient` | `auto` / `0` / `180` / `hflip` / `vflip` (live backend `reconfigure`) |
---
## 5. Configuration Reference (`config.json`)
Persisted atomically to `~/.config/czcamera/config.json` (override path with `CZCAMERA_CONFIG`). Malformed or missing configs fall back safely to defaults; out-of-range fields are sanitized on load.
| Field | Default | Valid Values / Range |
|---|---|---|
| `output_dir` | `"~/Pictures/czcamera"` | Target media folder (`~/` expanded via `$HOME`) |
| `theme` | `"dark"` | `"dark"`, `"light"` |
| `rail_side` | `"right"` | `"right"`, `"left"` |
| `photo_resolution` | `"8mp"` | `"8mp"` (`3280×2464`), `"2mp"` (`1640×1232`) |
| `photo_filter` | `"none"` | `"none"`, `"bw"`, `"hicon"`, `"sepia"`, `"cool"`, `"vivid"`, `"invert"`, `"retro"`, `"gameboy"` |
| `photo_timer_sec` | `0` | `0`, `3`, `10` |
| `grid_enabled` | `true` | `true`, `false` |
| `video_resolution` | `"720p"` | `"480p"`, `"720p"`, `"1080p"` |
| `video_audio` | `true` | `true`, `false` |
| `timelapse_resolution` | `"2mp"` | `"2mp"`, `"1080p"`, `"8mp"` |
| `timelapse_interval_sec` | `5` | `1..3600` (seconds) |
| `timelapse_output_mode` | `"video"` | `"video"`, `"photos"` |
| `timelapse_fps` | `24` | `15`, `24`, `30` |
| `timelapse_stop_mode` | `"manual"` | `"manual"`, `"shots"`, `"duration"` |
| `timelapse_stop_value` | `0` | `>= 0` (shot count or seconds when `"duration"`) |
| `timelapse_dim_sec` | `15` | `0..3600` (`0` = never auto-dim) |
| `ev` | `0.0` | `-2.0..2.0` |
| `camera_transform` | `"auto"` | `"auto"`, `"0"`, `"180"`, `"hflip"`, `"vflip"` |
---
## 6. CLI Options & Environment Variables
```text
czcamera [options]
--sim Run desktop 320x170 SDL2 simulator (uses mock camera)
--scale <1..4> Integer SDL2 window scale factor (default: 2)
--mock-cam Force procedural SimCameraBackend (desktop or device)
--output-dir <path> Override media output directory for this session (non-destructive to config.json)
--render-test <path.ppm> Render 320x170 P6 PPM snapshot headlessly and exit
--theme <dark|light> Initial theme override
--mode <photo|video|timelapse|gallery|settings>
Initial mode or modal
--rail <right|left> Control rail side override
--help Print usage help
```
Environment variables:
- `CZCAMERA_CONFIG`: Override path to `config.json`.
- `CZCAMERA_CAM_BIN`: Override path to `czcamera-cam` executable (default `/usr/bin/czcamera-cam`, with `./cam-helper/bin/czcamera-cam` development fallback).
---
## 7. Sync-Safe Storage & Disk Floor
- All in-progress files inside `output_dir` use leading dots so filesystem watchers/sync tools ignore partial writes:
- Photos: `.IMG_<ts>.jpg.tmp` → atomic `rename()` → `IMG_<ts>.jpg`
- Videos: `.VID_<ts>.mp4.part` → atomic `rename()` → `VID_<ts>.mp4`
- Timelapses: `.tl_work_<ts>/frame_0001.jpg` + `manifest.json`, `.TL_<ts>.mp4.part` → `TL_<ts>.mp4` or `TL_<ts>/`
- Minimum free storage floor: **`100 MB` (`104857600` bytes)** checked via `statvfs()` before any capture, every 2s during Video recording, and before each Timelapse shot.
---
## 8. Troubleshooting
- **"Camera Offline [R]" shown on device:**
1. Check `grep imx219 /boot/firmware/config.txt` (`dtoverlay=imx219`) and `rpicam-hello --list-cameras`.
2. Verify `/usr/bin/czcamera-cam --mock-driver --frame-fd 3` manually, or press `R` inside `czcamera` to respawn the backend.
- **Video records muted (`audio_unavailable` toast):** Check ALSA capture device visibility (`arecord -l` and `alsamixer`); `czcamera` automatically records muted video rather than dropping the shot.
- **Upside-down or mirrored preview on custom lens mount:** Open **Settings (`S`) → `Camera Orient`** and cycle `auto`, `0`, `180`, `hflip`, or `vflip`.