Initial commit

This commit is contained in:
Seth Hillbrand
2026-02-15 12:50:49 -08:00
commit c17ab8607c
61 changed files with 11607 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
__pycache__/
*.py[cod]
*.egg-info/
*.egg
dist/
build/
.venv/
+53
View File
@@ -0,0 +1,53 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
VENV := $(HOME)/.local/share/yolocam/venv
BIN := $(HOME)/.local/bin
UV := uv
COMMANDS := yolocam-ctl yolocam-gui
.PHONY: install install-gui-deps uninstall clean
install: $(VENV)/.installed
$(VENV)/.installed: yolocam-lib/pyproject.toml yolocam-ctl/pyproject.toml yolocam-gui/pyproject.toml
$(UV) venv --system-site-packages $(VENV)
VIRTUAL_ENV=$(VENV) $(UV) pip install -e yolocam-lib -e yolocam-ctl -e yolocam-gui
mkdir -p $(BIN)
ln -sf $(VENV)/bin/yolocam-ctl $(BIN)/yolocam-ctl
ln -sf $(VENV)/bin/yolocam-gui $(BIN)/yolocam-gui
touch $@
@echo ""
@echo "Installation complete. Commands available:"
@echo " yolocam-ctl -- camera control CLI"
@echo " yolocam-gui -- camera control GUI"
@echo ""
@echo "Ensure $(BIN) is on your PATH."
install-gui-deps:
sudo apt install -y \
python3-pyside6.qtcore \
python3-pyside6.qtgui \
python3-pyside6.qtwidgets \
python3-opencv
uninstall:
rm -f $(BIN)/yolocam-ctl $(BIN)/yolocam-gui
rm -rf $(VENV)
@echo "Uninstalled."
clean:
find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
find . -type d -name "*.egg-info" -exec rm -rf {} + 2>/dev/null || true
+109
View File
@@ -0,0 +1,109 @@
# YoloCam S3 Linux Tools
Linux control suite for the **YoloCam S3** USB webcam by YoloLiv (Yunxi Technology).
Provides a CLI tool and a PySide6 GUI for full camera parameter control over the
Yunxi protobuf protocol.
## Hardware
The YoloCam S3 (VID:PID `46f8:0855`) is a composite USB device exposing:
- **CDC NCM** network interface (192.168.126.10) for camera control
- **UVC** video class interface for live video feed
The camera runs BusyBox Linux on a HiSilicon HI3519DV500 SoC (aarch64, musl libc).
## Repository Structure
```
yolocam-lib/ Shared Python library (protocol, params, client, CLUT)
yolocam-ctl/ CLI tool for camera control
yolocam-gui/ PySide6 GUI application
docs/ User and technical documentation
```
## Quick Start
### Prerequisites
- Linux with USB support for CDC NCM
- Python 3.10+
- [uv](https://docs.astral.sh/uv/) (`curl -LsSf https://astral.sh/uv/install.sh | sh`)
### Installation
```bash
make install
```
This creates an isolated virtual environment at `~/.local/share/yolocam/venv`,
installs all three packages in editable mode, and symlinks `yolocam-ctl` and
`yolocam-gui` to `~/.local/bin/`.
For the GUI, also install PySide6 and OpenCV from system packages:
```bash
make install-gui-deps
```
Plug in the YoloCam S3 via USB. The CDC NCM interface should auto-configure via
DHCP (host gets 192.168.126.11).
### CLI
```bash
yolocam-ctl status # Check camera connection
yolocam-ctl list # List all parameters
yolocam-ctl get brightness # Read a parameter
yolocam-ctl set brightness 60 # Set a parameter
yolocam-ctl iso 400 # Set ISO
yolocam-ctl shutter 1000 # Set shutter to 1/1000s
yolocam-ctl monitor # Watch real-time notifications
```
![CLI status output](docs/screenshots/cli-status.png)
![CLI parameter listing](docs/screenshots/cli-get-all.png)
### GUI
```bash
yolocam-gui
```
The GUI auto-connects to the camera and displays the UVC video feed alongside
parameter controls for exposure, white balance, focus, zoom, color grading, and audio.
![GUI main window](docs/screenshots/gui-main.png)
![Color grading panel](docs/screenshots/gui-color-grading.png)
## Documentation
See the `docs/` directory for:
- [CLI User Guide](docs/cli-guide.md)
- [GUI User Guide](docs/gui-guide.md)
- [Protocol Technical Reference](docs/protocol-reference.md)
- [Device Access (Telnet/FTP)](docs/device-access.md)
## Protocol Overview
The camera is controlled via TCP on port 12345 using a custom dual-envelope wire
format wrapping protobuf `Message` payloads. All communication happens over the
CDC NCM USB network interface.
Wire format:
```
OUTER (8B): [0x08] [client_type] [0x00] [0x00] [LE32 inner_size]
INNER (6B): [0xA5] [BE32 proto_size] [XOR header_checksum]
PAYLOAD: [serialized protobuf Message]
TRAILER (2B):[XOR data_checksum] [0x5A]
```
See [Protocol Technical Reference](docs/protocol-reference.md) for complete details.
## License
This project is licensed under the [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.html)
or later. See the `LICENSE` file in each sub-project for the full license text.
+215
View File
@@ -0,0 +1,215 @@
# yolocam-ctl CLI User Guide
Command-line tool for controlling the YoloCam S3 camera on Linux.
## Prerequisites
1. YoloCam S3 connected via USB
2. CDC NCM network interface configured (host at 192.168.126.11, camera at 192.168.126.10)
3. `yolocam-lib` installed: `cd yolocam-lib && pip install -e .`
## Connection Setup
The camera exposes a CDC NCM network adapter over USB. Most Linux systems auto-configure
this via NetworkManager/DHCP. If not:
```bash
# Find the USB network interface
ip link show
# Configure manually
sudo ip link set usb0 up
sudo ip addr add 192.168.126.11/24 dev usb0
```
Verify connectivity:
```bash
yolocam-ctl status
```
## Commands
### status
Show camera connection status including USB detection, network, and firmware info.
```bash
yolocam-ctl status
```
Output:
```
YoloCam S3 Status
────────────────────────────────────
USB Device: Connected
Network: Interface configured
Control Port: Reachable (192.168.126.10:12345)
Firmware: YunxiCamera-ch131b-0.0.6
Serial: 524A25501202
ID: ...
```
### list
List all available camera parameters with read/write access and descriptions.
```bash
yolocam-ctl list
yolocam-ctl --json list # JSON output
```
Parameters are categorized: Image Quality, Zoom, Exposure, White Balance, Focus,
Video, Lens Correction, HDMI, Color / Tuning, Audio, LED / Indicator, AI Features,
Streaming, Device Info.
Access types:
- **RW** -- read and write
- **RO** -- read-only
- **WO** -- write-only (set commands only)
### get
Read one or more camera parameters.
```bash
yolocam-ctl get brightness
yolocam-ctl get brightness contrast saturation
yolocam-ctl --json get exposure-mode exposure-iso exposure-time
```
### get-all
Read all readable parameters. Automatically handles reconnection if the camera
stops responding.
```bash
yolocam-ctl get-all
yolocam-ctl --json get-all
```
### set
Set a camera parameter by name and value.
```bash
yolocam-ctl set brightness 60
yolocam-ctl set contrast 55
yolocam-ctl set exposure-mode 1 # 0=Auto, 1=Manual
yolocam-ctl set focus-mode 3 # 1=AFS, 2=Manual, 3=AFC, 4=Face
yolocam-ctl set hdr 1 # Enable HDR
yolocam-ctl set zoom 2.5 # 2.5x digital zoom (range 1.0-4.0)
```
### iso
Set ISO by actual value.
```bash
yolocam-ctl iso 400
yolocam-ctl iso 1600
```
Valid values: 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250,
1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 9600, 12800.
### shutter
Set shutter speed by denominator.
```bash
yolocam-ctl shutter 60 # 1/60s
yolocam-ctl shutter 1000 # 1/1000s
yolocam-ctl shutter 8000 # 1/8000s
```
Valid denominators: 25, 30, 50, 60, 80, 100, 125, 160, 200, 250, 320, 400,
500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000.
### wb-temp
Set white balance color temperature in Kelvin.
```bash
yolocam-ctl wb-temp 5500 # Daylight
yolocam-ctl wb-temp 3200 # Tungsten
yolocam-ctl wb-temp 7500 # Shade
```
Range: 2000K to 10000K. Requires `wb-mode` set to 0 (Manual).
### aperture
Set aperture by f-stop value. Finds the nearest supported value.
```bash
yolocam-ctl aperture 2.8
yolocam-ctl aperture F4.0
```
Note: The S3 has a fixed lens; aperture control applies to compatible YoloLiv lenses.
### raw
Send a raw protobuf command by numeric Command ID.
```bash
yolocam-ctl raw 7 # GET CID_BRIGHTNESS (CID 7)
yolocam-ctl raw 7 50 # SET CID_BRIGHTNESS to 50
```
Useful for exploring undocumented commands. See the proto file for all CID values.
### init
Run the full camera initialization sequence.
```bash
yolocam-ctl init
```
Sends heartbeat, queries firmware version, frame rate, aperture range, lens status,
USB version, and HDMI format.
### probe
Quick connectivity check verifying the wire format protocol works.
```bash
yolocam-ctl probe
```
### monitor
Watch real-time camera notifications (NOTIFY messages).
```bash
yolocam-ctl monitor
```
Shows timestamped notifications including parameter changes, face detection boxes,
recording state changes, and other events. Press Ctrl+C to stop.
## Global Options
| Option | Default | Description |
|--------|---------|-------------|
| `--ip` | 192.168.126.10 | Camera IP address |
| `--port` | 12345 | Camera control port |
| `--timeout` | 5.0 | Socket timeout in seconds |
| `--json` | off | Output in JSON format |
## Troubleshooting
**Connection refused**
- Check USB connection: `lsusb | grep 46f8:0855`
- Ensure network interface is up: `ip addr show`
- Try `yolocam-ctl status` for diagnostics
**Camera stops responding**
- The camera overwhelms easily with rapid requests
- Restart the camera app: `telnet 192.168.126.10` then `/app/bin/live_camera_app &`
- Or power-cycle the camera
**Timeout errors**
- Add `--timeout 10` for slow operations
- Some parameters (set-only) do not return responses
+138
View File
@@ -0,0 +1,138 @@
# YoloCam S3 Device Access
Technical reference for direct device access to the YoloCam S3 via Telnet and FTP
over the CDC NCM USB network interface.
## Network Setup
The camera exposes a CDC NCM (USB Ethernet) adapter alongside the UVC video interface.
When plugged in, the host system should auto-configure via DHCP.
| Role | IP Address | Subnet |
|------|------------|--------|
| Camera | 192.168.126.10 | /24 |
| Host | 192.168.126.11 | /24 |
If DHCP fails, configure manually:
```bash
sudo ip link set usb0 up
sudo ip addr add 192.168.126.11/24 dev usb0
ping 192.168.126.10
```
## Services
| Port | Protocol | Service | Credentials |
|------|----------|---------|-------------|
| 21 | TCP | FTP (BusyBox ftpd) | root / yunxi.tv |
| 23 | TCP | Telnet | root / yunxi.tv |
| 12345 | TCP | Camera control (protobuf) | None |
## Telnet Access
```bash
telnet 192.168.126.10
# Login: root
# Password: yunxi.tv
```
The shell is BusyBox ash. Standard coreutils are available as BusyBox applets.
### Hardware
| Property | Value |
|----------|-------|
| SoC | HiSilicon HI3519DV500 |
| Architecture | aarch64 |
| C library | musl libc |
| OS | BusyBox Linux |
| Firmware | YunxiCamera-ch131b-0.0.6 |
### Filesystem Layout
```
/app/bin/live_camera_app Main camera application (aarch64 ELF)
/app/ Application directory
/app_data/tuning/ Persistent tuning files (CLUT, scene presets)
/tmp/ Temporary runtime files
```
CLUT files are persisted as `/app_data/tuning/clut_{version}_{scene_id}.info` where
version and scene_id are integers (typically `clut_0_0.info`).
### Camera Application Management
The camera application (`live_camera_app`) handles all protocol communication, video
encoding, and ISP pipeline control. It binds TCP port 12345 for the control protocol.
**Check if running:**
```
ps | grep live_camera
```
**Restart the application:**
```
killall live_camera_app
/app/bin/live_camera_app &
```
Restarting is the primary recovery method when the camera stops responding to protocol
commands (typically caused by rapid-fire requests overwhelming the application).
**View application output:**
```
/app/bin/live_camera_app
```
Running in the foreground prints ISP and protocol debug messages to the console.
### System Information
```
cat /proc/cpuinfo # SoC details
cat /proc/meminfo # RAM usage
cat /proc/version # Kernel version
df -h # Disk usage
mount # Mounted filesystems
ifconfig # Network interfaces
```
## FTP Access
FTP provides read/write access to the camera filesystem. Useful for downloading
tuning files, logs, or firmware images.
```bash
ftp 192.168.126.10
# User: root
# Password: yunxi.tv
```
Or with a command-line client:
```bash
lftp -u root,yunxi.tv 192.168.126.10
```
### Common FTP Operations
**Download a CLUT tuning file:**
```
get /app_data/tuning/clut_0_0.info
```
**Browse the application directory:**
```
ls /app/bin/
```
## Caveats
- The camera has limited resources. Avoid running memory-intensive commands via telnet.
- Writing to flash storage (`/app/`, `/app_data/`) persists across reboots. Be careful
with modifications to these paths.
- `/tmp/` is a tmpfs and is cleared on reboot.
- The telnet and FTP services are always active on the CDC NCM interface. There is no
way to disable them without modifying the firmware.
- All access is as root with no privilege separation.
+167
View File
@@ -0,0 +1,167 @@
# YoloCam GUI User Guide
PySide6 desktop application for controlling the YoloCam S3 camera with live video preview.
## Prerequisites
1. YoloCam S3 connected via USB
2. CDC NCM network interface configured (camera at 192.168.126.10)
3. System packages:
```bash
sudo apt install python3-pyside6.qtcore python3-pyside6.qtgui \
python3-pyside6.qtwidgets python3-opencv
```
4. `yolocam-lib` installed: `cd yolocam-lib && pip install -e .`
**Important**: Use PySide6 from `apt`, not from `pip`. The pip version conflicts
with system Qt6 libraries.
## Launching
```bash
cd yolocam-gui
python run.py
```
The application auto-connects to the camera on startup and displays the UVC video feed.
## Interface Layout
```
┌──────┬─────────────────────┬──────────────────────────────────┐
│ │ │ │
│ Side │ Panel Area │ Video Feed │
│ bar │ (scrollable) │ (live UVC) │
│ │ │ │
│ [1] │ │ │
│ [2] │ │ │
│ [3] │ │ │
│ [4] │ │ │
│ [5] │ │ │
│ │ │ │
├──────┴─────────────────────┴──────────────────────────────────┤
│ Status bar │
└───────────────────────────────────────────────────────────────┘
```
## Panels
### 1. Camera Parameters (Ctrl+1)
Collapsible sections for all camera settings:
**Image Quality** -- Brightness, Sharpness (-10 to 30), Contrast, Saturation, Hue, Gamma
**Exposure** -- Mode (Auto/Manual), EV compensation, ISO, Shutter speed, Aperture,
Exposure Lock, Anti-flicker, Dynamic Range, HDR
**White Balance** -- Mode (Auto/Manual), Color Temperature (2000-10000K), WB Offset,
WB Lock
**Focus** -- Mode (AFS/Manual/AFC/Face), Focus Level (Large/Medium/Small), CAF toggle
**Zoom** -- Digital zoom slider (1.0x to 4.0x)
**Graphics** -- Noise Reduction (Close/Weak/Middle/Strong), Shading Correction
**Audio** -- Volume, Noise Reduction, Auto Gain, Mic Type, Reverb, Delay
### 2. Color Grading (Ctrl+2)
HSV color wheel with two grading modes:
**Fast Mode** -- Two-point color remapping. Click a source color region, drag to
the destination color. The shift propagates across the color space with linear falloff.
Multiple drags can be stacked. Changes are applied as a 3D Color LUT on the camera's ISP.
- Left-click: create a new color shift or drag an existing point
- Right-click: delete a drag point
- Hover over existing points to see which will be selected (enlarges)
- Reset Grid button: clear all adjustments
**Professional Mode** -- Per-point polar grid of draggable control points for
fine-grained HSV adjustments across the color space.
**HSV Sliders** -- Direct numeric control of Hue (0-360), Saturation (0-100),
Brightness (0-100).
**Color LUT** -- Enable/disable CLUT on camera, adjust intensity (0-255), reset grading.
**Tuning** -- Brightness and Color Temperature fine-tuning.
Switching from Fast to Professional mode syncs the grid state so professional mode
shows the result of fast mode edits.
### 3. Console (Ctrl+3)
Protocol console showing raw command/response traffic.
### 4. Stream (Ctrl+4)
Streaming and recording controls.
### 5. Settings (Ctrl+5)
Application configuration.
## Keyboard Shortcuts
| Shortcut | Action |
|----------|--------|
| Ctrl+Q | Quit |
| Ctrl+1 | Camera Parameters panel |
| Ctrl+2 | Color Grading panel |
| Ctrl+3 | Console panel |
| Ctrl+4 | Stream panel |
| Ctrl+5 | Settings panel |
| Ctrl+Shift+C | Toggle camera connection |
| F11 | Toggle fullscreen |
## Menu Bar
**YoloCam**
- Connect to Camera / Disconnect (Ctrl+Shift+C)
- Quit (Ctrl+Q)
**View**
- Panel shortcuts (Ctrl+1 through Ctrl+5)
- Toggle Fullscreen (F11)
## Color Grading Workflow
### Quick Color Correction (Fast Mode)
1. Select "Fast" mode at the top of the Color panel
2. Click on the color you want to change on the wheel
3. Drag to the target color
4. Release to commit. The CLUT is computed and sent to the camera
5. Add more adjustments by clicking and dragging other color regions
6. Use the Reset Grid button to start over
### Precise Color Grading (Professional Mode)
1. Select "Professional" mode
2. Drag individual grid points to shift specific color regions
3. Right-click a point to reset it to its home position
4. Right-click empty space to reset the entire grid
### Using the LUT Controls
1. Enable CLUT in the Color LUT section
2. Adjust Intensity (0-255) to control how strongly the LUT is applied
3. Use "Reset Color Grading" to clear the LUT and start fresh
## Troubleshooting
**Black video feed** -- The UVC device is auto-detected by VID/PID (46f8:0855).
Check `ls /dev/video*` and ensure the camera USB connection is stable.
**"Disconnected" in status bar** -- The camera may have dropped the TCP connection.
Use Ctrl+Shift+C to reconnect, or restart the application.
**Slider changes not applying** -- Ensure the camera is connected (status bar shows
"Connected"). Some parameters require specific modes (e.g., manual exposure mode for
ISO/shutter control).
**Color grading not visible** -- Enable CLUT in the Color LUT section and set
intensity above 0.
+508
View File
@@ -0,0 +1,508 @@
# YoloCam S3 Protocol Technical Reference
Complete documentation of the YoloCam S3 camera control protocol.
## Hardware Overview
| Property | Value |
|----------|-------|
| Manufacturer | YoloLiv (Yunxi Technology) |
| Model | YoloCam S3 |
| USB VID:PID | 46f8:0855 |
| SoC | HiSilicon HI3519DV500 |
| Architecture | aarch64, musl libc |
| OS | BusyBox Linux |
| Camera app | `/app/bin/live_camera_app` |
| Firmware | YunxiCamera-ch131b-0.0.6 |
| Sys code | 1188 |
### USB Interfaces
The camera is a composite USB device with two functional interfaces:
| Interface | Class | Function |
|-----------|-------|----------|
| 0-1 | CDC NCM | Network adapter (camera: 192.168.126.10, host: 192.168.126.11/24 via DHCP) |
| 2-3 | UVC | Video Class webcam (live video feed) |
### Network Services
On the CDC NCM network (192.168.126.10):
| Port | Service | Credentials |
|------|---------|-------------|
| 21 | FTP | root:yunxi.tv |
| 23 | Telnet | root:yunxi.tv |
| 12345 | Control protocol (TCP) | None |
## Wire Format
All control communication uses TCP on port 12345. Each message is wrapped in a
dual-envelope wire format.
### Frame Structure
```
Offset Size Field Description
────── ──── ──────────────────── ─────────────────────────────────────
0 1 outer_start Always 0x08
1 1 client_type 0x01 for client->camera, 0x00 for camera->client
2 2 padding Always 0x00 0x00
4 4 inner_size Little-endian uint32: proto_size + 8
8 1 inner_start Always 0xA5
9 4 proto_size Big-endian uint32: serialized protobuf length
13 1 header_checksum XOR of bytes [8..12] (inner_start + proto_size)
14 N payload Serialized protobuf Message
14+N 1 data_checksum XOR of all payload bytes
15+N 1 inner_end Always 0x5A
```
Total frame size: `16 + proto_size` bytes.
### Checksum Algorithm
Simple XOR of all bytes in the specified range:
```python
def xor_checksum(data: bytes) -> int:
result = 0
for b in data:
result ^= b
return result
```
The header checksum covers bytes 8-12 (inner start flag + 4-byte proto_size).
The data checksum covers the entire protobuf payload.
### Example Frame
Setting brightness to 50 (`CID_BRIGHTNESS = 7`, `value = 50`):
```
Protobuf Message:
type: TYPE_SET (2)
id: CID_BRIGHTNESS (7)
body: { int_val: 50 }
Serialized protobuf (hex): 08 02 28 07 32 02 08 32
proto_size = 8
Wire frame (hex):
08 01 00 00 10 00 00 00 Outer: start=0x08, client=0x01, inner_size=16
A5 00 00 00 08 AD Inner: start=0xA5, proto_size=8, hdr_xor=0xAD
08 02 28 07 32 02 08 32 Payload: protobuf bytes
0B 5A Trailer: data_xor=0x0B, end=0x5A
```
## Protobuf Schema
Package: `tv.yunxi.protobuf`
### Message Wrapper
```protobuf
message Message {
MessageType type = 1; // Request type
uint32 seq = 2; // Sequence number (echoed in response)
uint32 timeout = 3; // Request timeout (ms), typically 3000
uint32 resp_code = 4; // Response code (200=OK, 100=unsupported/out-of-range)
CommandId id = 5; // Which command
CommandBody body = 6; // Payload
}
```
### Message Types
| Value | Name | Description |
|-------|------|-------------|
| 1 | TYPE_REQUEST | Client reads a parameter (GET) |
| 2 | TYPE_SET | Client writes a parameter (SET) |
| 3 | TYPE_POST | Client sends data (file transfer, CLUT upload) |
| 4 | TYPE_RESPONSE | Camera response to any request |
| 5 | TYPE_NOTIFY | Asynchronous camera notification |
### Response Codes
| Code | Meaning |
|------|---------|
| 200 | Success |
| 100 | Unsupported command or value out of range |
### Command Body
```protobuf
message CommandBody {
oneof value {
uint32 int_val = 1;
string str_val = 2;
ManualExposureParams exposure_params = 3;
WhiteBalanceManual white_balance_manual = 4;
TransportFile transport_file = 5;
Size size = 6;
Range range = 7;
Rect rect = 8;
FileInfo file_info = 9;
VersionInfo version_info = 10;
UpgradeEvent upgrade_event = 11;
LensStatusEvent lens_event = 12;
WhiteBalanceOffset white_balance_offset = 13;
RectF rect_f = 14;
LensInfo lens_info = 15;
TuningFileInfo tuning_file_info = 16;
TuningParam tuning_param = 17;
ListInt list_int = 18;
ListRectF list_rect_f = 19;
LensDetail lens_detail = 20;
LensAmend lens_amend = 21;
LensReset lens_reset = 22;
BleScanParam ble_scan_param = 23;
AdvInfo adv_info = 24;
LightConnection light_connection = 25;
LightStatus light_status = 26;
LightParam light_param = 27;
LightConnectedList light_connected_list = 28;
IndicatorCtl indicator_ctl = 29;
RawImgInfo raw_img_info = 30;
TuningClutFile tuning_clut_file = 31;
WlanConf wlan_conf = 32;
StreamParam stream_param = 33;
DiskInfo disk_info = 34;
PtzCtrl ptz_ctrl = 35;
DumpPdParam dump_pd_param = 36;
RCEvent rc_event = 37;
WifiScanResults wifi_list = 38;
AiTrackingCtrl ai_tracking_ctrl = 39;
AiParams ai_params = 40;
VideoStatus video_status = 41;
DrawInfoList draw_info_list = 42;
AdvInfoList adv_list = 43;
LensVersionInfo lens_version_info = 44;
}
}
```
## Command Reference
### Image Quality
| CID | Name | Type | Range | Default | Description |
|-----|------|------|-------|---------|-------------|
| 7 | CID_BRIGHTNESS | int | 0-100 | 50 | Image brightness |
| 8 | CID_SHARPNESS | int | -10 to 30 | 5 | Sharpness. Wire encoding: 0-30 sent as-is, -1 to -10 sent as 61-70 |
| 9 | CID_CONTRAST | int | 0-100 | 50 | Contrast |
| 10 | CID_SATURATION | int | 0-100 | 50 | Color saturation |
| 11 | CID_HUE | int | 0-100 | 50 | Hue. Wire protocol 0-100 maps to UI 0-360 via `hue * 100 / 360` |
| 12 | CID_GAMMA | int | 0-100 | 50 | Gamma correction |
### Zoom
| CID | Name | Type | Range | Default | Description |
|-----|------|------|-------|---------|-------------|
| 13 | CID_ZOOM | int | 50-98 (raw) | 50 | Digital zoom. Conversion: `mult = 0.0625 * raw - 2.125`. Raw 50 = 1.0x, 98 = 4.0x |
| 112 | CID_ZOOM_SPEED | int | 1-5 | 3 | Zoom animation speed (set-only) |
### Exposure
| CID | Name | Type | Range | Default | Description |
|-----|------|------|-------|---------|-------------|
| 14 | CID_EXPOSURE_MODE | int | 0-1 | 0 | 0=Auto, 1=Manual |
| 15 | CID_EXPOSURE_EV | int | 0-16 | 8 | EV compensation. 8 = 0EV |
| 16 | CID_ANTI_FLICKER | int | 0-2 | 0 | 0=Off, 1=50Hz, 2=60Hz |
| 17 | CID_EXPOSURE_ISO | int | actual | 400 | ISO value sent directly (100, 125, ..., 12800) |
| 18 | CID_EXPOSURE_TIME | int | microseconds | 16666 | Shutter in microseconds (16666=1/60s, 1000=1/1000s, 125=1/8000s) |
| 20 | CID_EXPOSURE_APERTURE | int | 0-31 | 10 | Aperture index. 0=F1.0, 10=F2.8, 31=F32.0 |
| 98 | CID_ENABLE_HDR | int | 0-1 | 0 | HDR toggle |
| 102 | CID_DYNAMIC_RANGE | int | 0-100 | 50 | Dynamic range |
| 106 | CID_EXPOSURE_LOCK | int | 0-1 | 0 | Lock exposure |
#### Shutter Speed Table
| Denominator | Microseconds | | Denominator | Microseconds |
|-------------|--------------|--|-------------|--------------|
| 1/8000 | 125 | | 1/500 | 2000 |
| 1/6400 | 156 | | 1/400 | 2500 |
| 1/5000 | 200 | | 1/320 | 3125 |
| 1/4000 | 250 | | 1/250 | 4000 |
| 1/3200 | 312 | | 1/200 | 5000 |
| 1/2500 | 400 | | 1/160 | 6250 |
| 1/2000 | 500 | | 1/125 | 8000 |
| 1/1600 | 625 | | 1/100 | 10000 |
| 1/1250 | 800 | | 1/80 | 12500 |
| 1/1000 | 1000 | | 1/60 | 16666 |
| 1/800 | 1250 | | 1/50 | 20000 |
| 1/640 | 1562 | | 1/30 | 33333 |
| | | | 1/25 | 40000 |
#### ISO Values
100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000,
2500, 3200, 4000, 5000, 6400, 8000, 9600, 12800
### White Balance
| CID | Name | Type | Range | Default | Description |
|-----|------|------|-------|---------|-------------|
| 21 | CID_WHITE_BALANCE_MODE | int | 0-1 | 1 | 0=Manual, 1=Auto |
| 22 | CID_WHITE_BALANCE_TEMPERATURE | int | 2000-10000 | 5500 | Color temp in Kelvin |
| 33 | CID_WHITE_BALANCE_OFFSET | WhiteBalanceOffset | | | R/B offset (body.white_balance_offset) |
| 104 | CID_WHITE_BALANCE_LOCK | int | 0-1 | 0 | Lock WB |
| 105 | CID_WHITE_BALANCE_TEMPERATURE_SHIFT | int | 0-128 | 64 | WB temp shift |
### Focus
| CID | Name | Type | Range | Default | Description |
|-----|------|------|-------|---------|-------------|
| 23 | CID_FOCUS_MODE | int | 1-4 | 1 | 1=AFS, 2=Manual, 3=AFC, 4=Face |
| 38 | CID_FOCUS_RECT_LEVEL | int | 0-2 | 0 | 0=Large, 1=Medium, 2=Small |
| 42 | CID_ENABLE_CAF | int | 0-1 | 0 | Continuous AF |
| 47 | CID_TRIGGER_SPEED | int | | | AF trigger speed |
| 111 | CID_MANU_FOCUS_CODE | int | | | Manual focus step (set-only) |
| 214 | CID_ENABLE_FACE_ROI | int | 0-1 | 0 | Face-detect ROI (set-only) |
### Audio
| CID | Name | Type | Range | Default | Description |
|-----|------|------|-------|---------|-------------|
| 73 | CID_AU_VOLUME | int | 0-100 | 50 | Audio volume |
| 75 | CID_AU_DENOISE | int | 0-3 | 2 | 0=Close, 1=Weak, 2=Middle, 3=Strong |
| 76 | CID_AU_REVERB | int | 0-3 | 0 | 0=Close, 1=Weak, 2=Middle, 3=Strong |
| 77 | CID_AU_DELAY | int | 0-400 | 0 | Audio delay in ms |
| 78 | CID_AU_AUTO_GAIN | int | 0-1 | 0 | Auto gain toggle |
| 79 | CID_AU_MIC_TYPE | int | 0-1 | 0 | 0=Line, 1=Mic (set-only) |
### Video / Streaming
| CID | Name | Type | Range | Description |
|-----|------|------|-------|-------------|
| 5 | CID_FRAME_RATE | int | 25/30/50/60 | Frame rate |
| 6 | CID_RESOLUTION | int | | Resolution setting |
| 202 | CID_STREAM_CFG | StreamConfig | | Stream configuration (set-only) |
| 203 | CID_STREAMING_START | int | | Start streaming |
| 204 | CID_STREAMING_STOP | int | | Stop streaming |
| 205 | CID_RECORDING_START | int | | Start recording |
| 206 | CID_RECORDING_STOP | int | | Stop recording |
| 211 | CID_ENABLE_UVC | int | 0-1 | UVC output (set-only) |
### HDMI
| CID | Name | Type | Range | Default | Description |
|-----|------|------|-------|---------|-------------|
| 61 | CID_HDMI_OUTPUT_FORMAT | int | 0-3 | 0 | 0=Auto, 1=4K, 2=1080p, 3=720p |
| 65 | CID_HDMI_COLOR_SPACE | int | 0-2 | 0 | 0=Auto, 1=RGB, 2=YUV422 |
### Color LUT (CLUT)
| CID | Name | Type | Description |
|-----|------|------|-------------|
| 94 | CID_ENABLE_CLUT | int (0/1) | Enable/disable 3D color LUT on ISP |
| 95 | CID_CLUT_FILE | TuningClutFile | Upload CLUT data (5508 uint32 entries) |
| 96 | CID_CLUT_ATTR | int (0-255) | CLUT blend intensity |
| 53 | CID_TUNING | TuningParam | Image tuning (brightness, curve, color_temp) |
#### CLUT Data Format
The ISP uses a 17x17x17 3D color lookup table stored as 5508 uint32 entries in an
interleaved octant layout. Each uint32 packs three signed 10-bit RGB delta values
in s0.9 fixed-point format (range [-1.0, +0.998]).
**Entry packing**: `(R_delta << 20) | (G_delta << 10) | B_delta`
Each 10-bit delta is interpreted as signed fixed-point divided by 512:
- Value 0: no change
- Value 511: +0.998 (maximum positive delta)
- Value 512 (0x200): -1.0 (maximum negative delta, two's complement)
**Octant interleaving**: The 4913 grid nodes (17^3) are grouped into 8 octants based
on the parity of (x, y, z) indices. Octant = `(x&1) + ((y&1)<<1) + ((z&1)<<2)`.
| Octant | Even/Odd pattern | Size | Cumulative offset |
|--------|-----------------|------|-------------------|
| 0 | (E,E,E) | 729 (9x9x9) | 0 |
| 1 | (O,E,E) | 648 (8x9x9) | 729 |
| 2 | (E,O,E) | 648 (9x8x9) | 1377 |
| 3 | (O,O,E) | 576 (8x8x9) | 2025 |
| 4 | (E,E,O) | 648 (9x9x8) | 2601 |
| 5 | (O,E,O) | 576 (8x9x8) | 3249 |
| 6 | (E,O,O) | 576 (9x8x8) | 3825 |
| 7 | (O,O,O) | 512 (8x8x8) | 4401 |
Total: 729+648+648+576+648+576+576+512 = 4913 entries (with 595 padding to 5508).
**Upload via protobuf**: CLUT data is sent using `TuningClutFile` message on
`CID_CLUT_FILE (95)` as a TYPE_POST:
```protobuf
message TuningClutFile {
uint32 clut_size = 1; // Always 5508
repeated uint32 clut_data = 2; // The CLUT entries
string hsv_data = 3; // JSON string with HSV grid state
string extra = 4; // Additional metadata
string updataflag = 5; // Update flag
}
```
### AI Features
| CID | Name | Type | Range | Default | Description |
|-----|------|------|-------|---------|-------------|
| 99 | CID_AI_TRACKING_CTRL | AiTrackingCtrl | 0-2 | 2 | 0=Portrait, 1=Thing, 2=Off |
| 59 | CID_FACE_BOUNDING_BOXES | ListRectF | | | Face detection boxes (NOTIFY, fires constantly) |
### Device Info (Read-Only)
| CID | Name | Response Type | Description |
|-----|------|--------------|-------------|
| 1 | CID_VERSION_INFO | VersionInfo | Firmware version, serial, unique ID, sys_code |
| 60 | CID_USB_VERSION | int | USB protocol version |
| 48 | CID_LENS_STATUS | int | Lens connection status |
| 63 | CID_GET_LENS_DETAIL | LensDetail | Lens ID, aperture, focal, serial, drive times |
| 113 | CID_LENS_VERSION | LensVersionInfo | Lens firmware version |
| 210 | CID_VIDEO_STATUS_CHANGED | VideoStatus | Video pipeline status |
| 103 | CID_AU_VERSION | int | Audio module version |
| 301 | CID_DISK_INFO | DiskInfo | SD card total/available size, filesystem type |
| 213 | CID_LOWPOWER_STATUS | int | Low power status |
| 31 | CID_RANGE_OF_APERTURE | Range | Min/max aperture for current lens |
| 32 | CID_RANGE_OF_EXP_TIME | Range | Min/max exposure time range |
### Notifications
| CID | Name | Description |
|-----|------|-------------|
| 59 | CID_FACE_BOUNDING_BOXES | Face detection rectangles (high frequency, suppress in logs) |
| 209 | CID_DURATION_CHANGED | Recording duration update |
| 210 | CID_VIDEO_STATUS_CHANGED | Video pipeline state change |
| 207 | CID_STREAMING_STOPPED | Streaming stopped |
| 208 | CID_RECORDING_FINISHED | Recording finished |
| 303 | CID_DISK_EVENT | SD card insertion/removal |
### Heartbeat
The camera requires a periodic heartbeat to maintain the control connection:
```
CID_STREAM_HEARTBEAT (215) = 1, sent every 30 seconds
```
If the heartbeat stops, the camera may drop the TCP connection.
## Communication Patterns
### GET (Read Parameter)
```
Client -> Camera:
Message {
type: TYPE_REQUEST (1)
seq: N
timeout: 3000
id: CID_BRIGHTNESS (7)
}
Camera -> Client:
Message {
type: TYPE_RESPONSE (4)
seq: N
resp_code: 200
id: CID_BRIGHTNESS (7)
body: { int_val: 50 }
}
```
### SET (Write Parameter)
```
Client -> Camera:
Message {
type: TYPE_SET (2)
seq: N
timeout: 3000
id: CID_BRIGHTNESS (7)
body: { int_val: 60 }
}
Camera -> Client:
Message {
type: TYPE_RESPONSE (4)
seq: N
resp_code: 200
id: CID_BRIGHTNESS (7)
}
```
### POST (Send Complex Data)
Used for CLUT uploads, file transfers, and other structured data:
```
Client -> Camera:
Message {
type: TYPE_POST (3)
seq: N
timeout: 3000
id: CID_CLUT_FILE (95)
body: {
tuning_clut_file: {
clut_size: 5508
clut_data: [0, 0, 0, ..., 5508 entries]
hsv_data: "{\"hue\": [...], \"sat\": [...]}"
}
}
}
```
### NOTIFY (Camera Event)
Unsolicited messages from camera to client:
```
Camera -> Client:
Message {
type: TYPE_NOTIFY (5)
id: CID_FACE_BOUNDING_BOXES (59)
body: { list_rect_f: { values: [...] } }
}
```
## Camera Behavior Notes
### Rate Limiting
The camera overwhelms easily with rapid requests. After approximately 25+ rapid
requests without delays, it stops responding to all commands except CID_VERSION_INFO.
Mitigation:
- Insert 100ms+ delays between requests
- Use single persistent TCP connections
- Restart `live_camera_app` via telnet if camera becomes unresponsive
### Recovery
If the camera stops responding:
```bash
telnet 192.168.126.10
# Login: root / yunxi.tv
killall live_camera_app
/app/bin/live_camera_app &
```
Or power-cycle the camera.
### Set-Only Parameters
Some parameters only accept SET commands and return resp_code=100 for GET:
CID_ZOOM_SPEED, CID_MANU_FOCUS_CODE, CID_ENABLE_FACE_ROI, CID_SCENE,
CID_STREAM_CFG, CID_ENABLE_UVC, CID_AU_MIC_TYPE, CID_INDICATOR_CTL
### Filesystem
The camera's filesystem (accessible via FTP at root:yunxi.tv):
```
/app/bin/live_camera_app Main camera application
/app/ Application directory
/tmp/ Temporary files (CLUT saves go here)
```
CLUT files are persisted as `/tmp/clut_0_0.info` on the camera's filesystem.
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 473 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 400 KiB

+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+19
View File
@@ -0,0 +1,19 @@
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "yolocam-ctl"
version = "0.1.0"
description = "CLI tool for controlling YoloCam S3 camera parameters"
license = "GPL-3.0-or-later"
requires-python = ">=3.10"
dependencies = [
"yolocam",
]
[project.scripts]
yolocam-ctl = "yolocam_ctl.cli:main"
[tool.setuptools.packages.find]
include = ["yolocam_ctl*"]
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Standalone launcher for yolocam-ctl (delegates to yolocam_ctl.cli)."""
from yolocam_ctl.cli import main
if __name__ == "__main__":
main()
+14
View File
@@ -0,0 +1,14 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
+777
View File
@@ -0,0 +1,777 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
yolocam-ctl - Linux CLI for controlling YoloCam S3 camera parameters
Communicates with the camera over its CDC NCM USB network interface using the
reverse-engineered Yunxi protobuf protocol (TCP port 12345).
Protocol discovered by reverse engineering SocketPacketPolicy::pack() in ycc.dylib.
Wire format (SocketPacketPolicy dual-envelope):
OUTER (8 bytes): [0x08] [client_type] [0x00] [0x00] [LE32 inner_size]
INNER (6 bytes): [0xA5] [BE32 proto_size] [XOR header_checksum]
PAYLOAD (N bytes): [serialized protobuf]
TRAILER (2 bytes): [XOR data_checksum] [0x5A]
client_type: 0x01 for client, 0x00 for camera responses
inner_size: proto_size + 8 (inner header + checksums + trailer)
"""
import argparse
import json
import socket
import subprocess
import sys
import textwrap
import time
from yolocam.client import YoloCamClient
from yolocam.params import (
PARAMS, PARAM_CATEGORIES,
ISO_VALUES, SHUTTER_TABLE, SHUTTER_REVERSE, APERTURE_TABLE,
ZOOM_MULT_MIN, ZOOM_MULT_MAX,
zoom_raw_to_mult, zoom_mult_to_raw, find_nearest_aperture,
is_readable, is_writable,
)
from yolocam.protocol import CAMERA_IP, CAMERA_PORT, DEFAULT_TIMEOUT
from yolocam import yolocam_pb2 as pb
def format_response(resp, param_name=None):
"""Format a protobuf response message for CLI display.
Returns a dict suitable for JSON output or human-readable formatting.
"""
if resp is None:
return "No response from camera"
result = {}
result["resp_code"] = resp.resp_code
result["command"] = pb.CommandId.Name(resp.id) if resp.id else "NONE"
if resp.HasField("body"):
body = resp.body
which = body.WhichOneof("value")
if which == "int_val":
val = body.int_val
result["value"] = val
if param_name == "zoom":
result["zoom_mult"] = zoom_raw_to_mult(val)
elif param_name == "exposure-iso" and val in ISO_VALUES:
result["iso"] = val
elif param_name == "exposure-time" and val in SHUTTER_REVERSE:
result["shutter_speed"] = f"1/{SHUTTER_REVERSE[val]}"
elif param_name == "exposure-aperture" and val in APERTURE_TABLE:
result["aperture"] = APERTURE_TABLE[val]
elif which == "str_val":
result["value"] = body.str_val
elif which == "version_info":
vi = body.version_info
result["sys_version"] = vi.sys_version
result["unique_id"] = vi.unique_id
result["serial_num"] = vi.serial_num
result["sys_code"] = vi.sys_code
elif which == "exposure_params":
ep = body.exposure_params
result["iso"] = ep.iso
result["shutter_us"] = ep.shutter
if ep.shutter in SHUTTER_REVERSE:
result["shutter_speed"] = f"1/{SHUTTER_REVERSE[ep.shutter]}"
result["aperture_index"] = ep.aperture
if ep.aperture in APERTURE_TABLE:
result["aperture"] = APERTURE_TABLE[ep.aperture]
elif which == "white_balance_manual":
wb = body.white_balance_manual
result["saturation"] = wb.saturation
result["chroma"] = wb.chroma
elif which == "white_balance_offset":
wbo = body.white_balance_offset
result["red_offset"] = wbo.offset_r
result["blue_offset"] = wbo.offset_b
elif which == "lens_detail":
ld = body.lens_detail
result["lens_id"] = ld.lens_id
result["aperture"] = ld.aperture
result["focal"] = ld.focal
result["detected"] = ld.detected
result["serial"] = ld.serino
elif which == "stream_param":
sp = body.stream_param
if sp.HasField("venc_param"):
v = sp.venc_param
result["video"] = {
"codec": v.codec, "width": v.width, "height": v.height,
"bitrate": v.bitrate, "fps": v.rate, "profile": v.profile,
}
if sp.HasField("aenc_param"):
a = sp.aenc_param
result["audio"] = {
"codec": a.codec, "channels": a.channels,
"sample_rate": a.sample_rate, "bitrate": a.bitrate,
}
elif which == "video_status":
result["video_status"] = body.video_status.status
elif which == "range":
result["min"] = body.range.min
result["max"] = body.range.max
elif which == "disk_info":
di = body.disk_info
result["total_size"] = di.total_size
result["available_size"] = di.available_size
result["fs_type"] = di.fs_type
result["smb_path"] = di.smb_path
elif which == "lens_version_info":
lvi = body.lens_version_info
result["current_version"] = lvi.current_version
result["latest_version"] = lvi.latest_version
elif which is not None:
result["body_type"] = which
result["raw"] = str(getattr(body, which))
return result
def ensure_network_interface():
"""Ensure the CDC NCM interface to the camera is up and configured."""
try:
result = subprocess.run(
["ip", "route", "get", CAMERA_IP],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0 and CAMERA_IP in result.stdout:
return True
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
# Find the CDC NCM interface (usb0 or similar)
try:
result = subprocess.run(
["ip", "-o", "link", "show"],
capture_output=True, text=True, timeout=5
)
for line in result.stdout.splitlines():
parts = line.split(":")
if len(parts) >= 2:
iface = parts[1].strip()
if iface in ("lo", "wlo1") or iface.startswith(("enp", "vmnet", "br-", "docker", "veth")):
continue
if "usb" in iface.lower() or iface.startswith("enx"):
subprocess.run(
["sudo", "ip", "link", "set", iface, "up"],
capture_output=True, timeout=5
)
subprocess.run(
["sudo", "ip", "addr", "add", "192.168.126.11/24",
"dev", iface],
capture_output=True, timeout=5
)
time.sleep(1)
return True
except (subprocess.TimeoutExpired, FileNotFoundError):
pass
return False
def check_camera_reachable():
"""Quick TCP connect test to see if the camera control port is reachable."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect((CAMERA_IP, CAMERA_PORT))
s.close()
return True
except (socket.timeout, socket.error, OSError):
return False
def cmd_get(args):
"""Get one or more camera parameters over a single connection."""
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
for param_name in args.params:
pdef = PARAMS.get(param_name)
if pdef is None:
print(f"Unknown parameter: {param_name}", file=sys.stderr)
print(f"Use 'yolocam-ctl list' to see available parameters", file=sys.stderr)
continue
if not is_readable(pdef):
print(f"{param_name}: (set-only, use 'set' command)")
continue
try:
resp = client.request(pdef.cid, recv_timeout=3.0)
result = format_response(resp, param_name)
except socket.timeout:
print(f"{param_name}: (no response)")
continue
if args.json:
result["parameter"] = param_name
print(json.dumps(result, indent=2))
else:
if "value" in result:
if "zoom_mult" in result:
print(f"{param_name}: {result['zoom_mult']:.1f}x")
elif "iso" in result and param_name == "exposure-iso":
print(f"{param_name}: {result['value']} (ISO {result['iso']})")
elif "shutter_speed" in result and param_name == "exposure-time":
print(f"{param_name}: {result['value']} ({result['shutter_speed']}s)")
elif "aperture" in result and param_name == "exposure-aperture":
print(f"{param_name}: {result['value']} ({result['aperture']})")
else:
print(f"{param_name}: {result['value']}")
elif "sys_version" in result:
print(f"Firmware: {result['sys_version']}")
print(f"Serial: {result['serial_num']}")
print(f"ID: {result['unique_id']}")
else:
print(f"{param_name}: {json.dumps(result, indent=2)}")
finally:
client.close()
def cmd_set(args):
"""Set a camera parameter."""
param_name = args.param
pdef = PARAMS.get(param_name)
if pdef is None:
print(f"Unknown parameter: {param_name}", file=sys.stderr)
sys.exit(1)
if not is_writable(pdef):
print(f"Parameter '{param_name}' is read-only", file=sys.stderr)
sys.exit(1)
if pdef.control_type == "zoom":
mult = float(args.value)
if mult < ZOOM_MULT_MIN or mult > ZOOM_MULT_MAX:
print(
f"Zoom {mult:.1f}x is out of range. Valid range is {ZOOM_MULT_MIN:.1f}x to {ZOOM_MULT_MAX:.1f}x.",
file=sys.stderr,
)
sys.exit(1)
value = zoom_mult_to_raw(mult)
else:
value = int(args.value)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pdef.cid, value)
result = format_response(resp, param_name)
if args.json:
result["parameter"] = param_name
result["set_value"] = value
print(json.dumps(result, indent=2))
else:
rc = result.get("resp_code", -1)
if rc == 200:
if pdef.control_type == "zoom":
print(f"{param_name} = {zoom_raw_to_mult(value):.1f}x (OK)")
else:
print(f"{param_name} = {value} (OK)")
else:
print(f"{param_name} = {value} (resp_code={rc})")
finally:
client.close()
def cmd_set_iso(args):
"""Set ISO by actual value (100, 200, 400, etc.)."""
iso_val = int(args.value)
if iso_val not in ISO_VALUES:
print(f"Invalid ISO value: {iso_val}", file=sys.stderr)
print(f"Valid values: {ISO_VALUES}", file=sys.stderr)
sys.exit(1)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pb.CID_EXPOSURE_ISO, iso_val)
result = format_response(resp)
rc = result.get("resp_code", -1)
print(f"ISO {iso_val} {'OK' if rc == 200 else f'resp_code={rc}'}")
finally:
client.close()
def cmd_set_shutter(args):
"""Set shutter speed by denominator (e.g., 1000 for 1/1000s)."""
speed = int(args.value)
if speed not in SHUTTER_TABLE:
print(f"Invalid shutter speed: 1/{speed}", file=sys.stderr)
valid = sorted(SHUTTER_TABLE.keys(), reverse=True)
print(f"Valid values: {['1/' + str(v) for v in valid]}", file=sys.stderr)
sys.exit(1)
us = SHUTTER_TABLE[speed]
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pb.CID_EXPOSURE_TIME, us)
result = format_response(resp)
rc = result.get("resp_code", -1)
print(f"Shutter 1/{speed}s ({us}us) {'OK' if rc == 200 else f'resp_code={rc}'}")
finally:
client.close()
def cmd_set_wb_temp(args):
"""Set white balance temperature in Kelvin."""
temp = int(args.value)
if temp < 2000 or temp > 10000:
print(f"Temperature should be 2000-10000K, got {temp}", file=sys.stderr)
sys.exit(1)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pb.CID_WHITE_BALANCE_TEMPERATURE, temp)
result = format_response(resp)
rc = result.get("resp_code", -1)
print(f"White balance {temp}K {'OK' if rc == 200 else f'resp_code={rc}'}")
finally:
client.close()
def cmd_set_aperture(args):
"""Set aperture by f-stop value (e.g., 2.8 for F2.8)."""
target = args.value.upper().lstrip("F")
try:
target_f = float(target)
except ValueError:
print(f"Invalid aperture: {args.value}", file=sys.stderr)
sys.exit(1)
best_idx = find_nearest_aperture(target_f)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.set_int(pb.CID_EXPOSURE_APERTURE, best_idx)
result = format_response(resp)
rc = result.get("resp_code", -1)
print(f"Aperture {APERTURE_TABLE[best_idx]} (index {best_idx}) "
f"{'OK' if rc == 200 else f'resp_code={rc}'}")
finally:
client.close()
def cmd_list(args):
"""List all available parameters."""
if args.json:
out = {}
for name, pdef in PARAMS.items():
out[name] = {"id": pdef.cid, "description": pdef.description, "type": pdef.control_type}
print(json.dumps(out, indent=2))
return
for category, names in PARAM_CATEGORIES.items():
print(f"\n {category}")
print(f" {'─' * len(category)}")
for name in names:
pdef = PARAMS.get(name)
if pdef is None:
continue
if not is_readable(pdef):
rw = "WO"
elif not is_writable(pdef):
rw = "RO"
else:
rw = "RW"
print(f" {name:<22} [{rw}] {pdef.description}")
def cmd_get_all(args):
"""Get all readable parameters, reconnecting as needed."""
results = {}
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
consecutive_timeouts = 0
try:
for name, pdef in PARAMS.items():
if not is_readable(pdef):
continue
try:
resp = client.request(pdef.cid, recv_timeout=3.0)
result = format_response(resp, name)
results[name] = result
consecutive_timeouts = 0
except socket.timeout:
results[name] = {"error": "no response"}
consecutive_timeouts += 1
if consecutive_timeouts >= 2:
try:
client.close()
except Exception:
pass
time.sleep(0.5)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
consecutive_timeouts = 0
except Exception as e:
results[name] = {"error": str(e)}
time.sleep(0.1)
finally:
client.close()
if args.json:
print(json.dumps(results, indent=2))
else:
for name, result in results.items():
rc = result.get("resp_code", -1)
if "error" in result:
print(f"{name}: ({result['error']})")
elif rc == 100:
print(f"{name}: (unsupported)")
elif "zoom_mult" in result:
print(f"{name}: {result['zoom_mult']:.1f}x")
elif "value" in result:
print(f"{name}: {result['value']}")
elif "sys_version" in result:
print(f"{name}: {result.get('sys_version', 'N/A')}")
else:
print(f"{name}: {result}")
def cmd_init(args):
"""Initialize camera connection following the Windows app sequence."""
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
print(f"Connected to {args.ip}:{args.port}")
print("Sending heartbeat...")
client.set_int(pb.CID_STREAM_HEARTBEAT, 1)
print("Checking camera status...")
resp = client.request(pb.CID_LOWPOWER_STATUS)
result = format_response(resp)
print(f" Low power status: {result.get('value', result)}")
print("Querying device info...")
resp = client.request(pb.CID_VERSION_INFO)
result = format_response(resp, "version")
if "sys_version" in result:
print(f" Firmware: {result['sys_version']}")
print(f" Serial: {result['serial_num']}")
print(f" ID: {result['unique_id']}")
init_params = [
(pb.CID_FRAME_RATE, "Frame rate"),
(pb.CID_RANGE_OF_APERTURE, "Aperture range"),
(pb.CID_LENS_STATUS, "Lens status"),
(pb.CID_USB_VERSION, "USB version"),
(pb.CID_HDMI_OUTPUT_FORMAT, "HDMI format"),
]
print("Querying camera parameters...")
for cid, name in init_params:
try:
resp = client.request(cid)
result = format_response(resp)
val = result.get("value", result.get("min", result))
print(f" {name}: {val}")
except Exception as e:
print(f" {name}: error ({e})")
print("Camera initialized successfully")
finally:
client.close()
def cmd_raw(args):
"""Send a raw command by numeric ID."""
cid = int(args.command_id)
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
if args.value is not None:
resp = client.set_int(cid, int(args.value))
else:
resp = client.request(cid)
result = format_response(resp)
print(json.dumps(result, indent=2))
finally:
client.close()
def cmd_probe(args):
"""Probe the camera TCP port and verify protocol connectivity."""
print(f"Probing camera at {args.ip}:{args.port}...")
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
try:
resp = client.request(pb.CID_VERSION_INFO)
result = format_response(resp, "version")
print(f"Protocol OK (resp_code={result.get('resp_code', 'N/A')})")
if "sys_version" in result:
print(f" Firmware: {result['sys_version']}")
print(f" Serial: {result['serial_num']}")
except Exception as e:
print(f"Probe failed: {e}")
finally:
client.close()
def cmd_monitor(args):
"""Monitor camera notifications in real-time."""
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
print(f"Connected to camera at {args.ip}:{args.port}")
# Send initial heartbeat (background thread already started by connect())
client.set_int(pb.CID_STREAM_HEARTBEAT, 1)
print("Monitoring notifications (Ctrl+C to stop)...")
print()
try:
client._sock.settimeout(None)
while True:
try:
resp = client._recv_one_message()
if resp:
ts = time.strftime("%H:%M:%S")
cmd_name = pb.CommandId.Name(resp.id) if resp.id else "NONE"
type_name = pb.MessageType.Name(resp.type)
result = format_response(resp)
print(f"[{ts}] {type_name} {cmd_name}: {json.dumps(result)}")
except Exception as e:
print(f"Error: {e}")
break
except KeyboardInterrupt:
print("\nStopped.")
finally:
client.close()
def cmd_status(args):
"""Show camera connection status and basic info."""
print("YoloCam S3 Status")
print("─" * 40)
try:
result = subprocess.run(
["lsusb"], capture_output=True, text=True, timeout=5
)
found = any("46f8:0855" in line for line in result.stdout.splitlines())
print(f"USB Device: {'Connected' if found else 'Not found'}")
except Exception:
print("USB Device: Unknown (lsusb failed)")
net_ok = ensure_network_interface()
print(f"Network: {'Interface configured' if net_ok else 'No interface'}")
tcp_ok = check_camera_reachable()
print(f"Control Port: {'Reachable' if tcp_ok else 'Not reachable'} ({CAMERA_IP}:{CAMERA_PORT})")
if tcp_ok:
try:
client = YoloCamClient(args.ip, args.port, args.timeout)
client.connect()
resp = client.request(pb.CID_VERSION_INFO)
result = format_response(resp, "version")
client.close()
if "sys_version" in result:
print(f"Firmware: {result['sys_version']}")
print(f"Serial: {result['serial_num']}")
print(f"ID: {result['unique_id']}")
except Exception as e:
print(f"Info: Failed to query ({e})")
def main():
parser = argparse.ArgumentParser(
prog="yolocam-ctl",
description="Control YoloCam S3 camera parameters on Linux",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent("""\
Examples:
yolocam-ctl status Show camera connection status
yolocam-ctl list List all available parameters
yolocam-ctl get brightness contrast Get current values
yolocam-ctl get-all Get all parameters
yolocam-ctl set brightness 50 Set brightness to 50
yolocam-ctl set exposure-mode 1 Switch to manual exposure
yolocam-ctl iso 400 Set ISO to 400
yolocam-ctl shutter 1000 Set shutter to 1/1000s (1000us)
yolocam-ctl wb-temp 5500 Set white balance to 5500K
yolocam-ctl aperture 2.8 Set aperture to F2.8
yolocam-ctl set zoom 2.0 Set 2.0x digital zoom
yolocam-ctl set hdr 1 Enable HDR
yolocam-ctl set focus-mode 3 Switch to continuous AF
yolocam-ctl init Full camera initialization
yolocam-ctl monitor Watch real-time notifications
yolocam-ctl raw 7 Query raw command ID 7
yolocam-ctl raw 7 50 Set raw command ID 7 to 50
"""),
)
parser.add_argument("--ip", default=CAMERA_IP, help=f"Camera IP (default: {CAMERA_IP})")
parser.add_argument("--port", type=int, default=CAMERA_PORT, help=f"Camera port (default: {CAMERA_PORT})")
parser.add_argument(
"--timeout", type=float, default=DEFAULT_TIMEOUT, help=f"Socket timeout (default: {DEFAULT_TIMEOUT}s)"
)
parser.add_argument("--json", action="store_true", help="Output in JSON format")
sub = parser.add_subparsers(dest="command", help="Command to execute")
sub.add_parser("status", help="Show camera connection status and info")
sub.add_parser("list", help="List all available parameters")
sub.add_parser("init", help="Initialize camera (mimics Windows app startup)")
p_get = sub.add_parser("get", help="Get camera parameter(s)")
p_get.add_argument("params", nargs="+", help="Parameter name(s)")
sub.add_parser("get-all", help="Get all camera parameters")
p_set = sub.add_parser("set", help="Set a camera parameter")
p_set.add_argument("param", help="Parameter name")
p_set.add_argument("value", help="Value to set")
p_iso = sub.add_parser("iso", help="Set ISO by value (100, 200, 400, ...)")
p_iso.add_argument("value", help="ISO value")
p_shutter = sub.add_parser("shutter", help="Set shutter speed (denominator, e.g., 1000 for 1/1000s)")
p_shutter.add_argument("value", help="Shutter speed denominator")
p_wb = sub.add_parser("wb-temp", help="Set white balance temperature in Kelvin")
p_wb.add_argument("value", help="Temperature in K (2000-10000)")
p_ap = sub.add_parser("aperture", help="Set aperture by f-stop (e.g., 2.8 or F2.8)")
p_ap.add_argument("value", help="F-stop value")
p_raw = sub.add_parser("raw", help="Send raw command by numeric ID")
p_raw.add_argument("command_id", help="Numeric command ID")
p_raw.add_argument("value", nargs="?", help="Value to set (omit for GET)")
sub.add_parser("probe", help="Probe camera TCP port to detect framing protocol")
sub.add_parser("monitor", help="Monitor real-time camera notifications")
args = parser.parse_args()
if not args.command:
parser.print_help()
sys.exit(0)
dispatch = {
"status": cmd_status,
"list": cmd_list,
"init": cmd_init,
"get": cmd_get,
"get-all": cmd_get_all,
"set": cmd_set,
"iso": cmd_set_iso,
"shutter": cmd_set_shutter,
"wb-temp": cmd_set_wb_temp,
"aperture": cmd_set_aperture,
"raw": cmd_raw,
"probe": cmd_probe,
"monitor": cmd_monitor,
}
try:
dispatch[args.command](args)
except ConnectionRefusedError:
print("Connection refused. Is the camera connected and the network interface up?", file=sys.stderr)
print(f"Try: yolocam-ctl status", file=sys.stderr)
sys.exit(1)
except socket.timeout:
print("Connection timed out. Camera may not be reachable.", file=sys.stderr)
sys.exit(1)
except OSError as e:
if "Network is unreachable" in str(e):
print("Network unreachable. The CDC NCM interface may not be configured.", file=sys.stderr)
print("Try: sudo dhclient <interface> OR yolocam-ctl status", file=sys.stderr)
else:
print(f"Network error: {e}", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
sys.exit(0)
if __name__ == "__main__":
main()
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+19
View File
@@ -0,0 +1,19 @@
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "yolocam-gui"
version = "0.1.0"
description = "PySide6 GUI for controlling YoloCam S3 camera"
license = "GPL-3.0-or-later"
requires-python = ">=3.10"
dependencies = [
"yolocam",
]
[project.scripts]
yolocam-gui = "yolocam_gui.app:run"
[tool.setuptools.packages.find]
include = ["yolocam_gui*"]
+3
View File
@@ -0,0 +1,3 @@
yolocam
PySide6>=6.5
opencv-python>=4.8
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Launch YoloCam."""
from yolocam_gui.app import run
if __name__ == "__main__":
run()
+18
View File
@@ -0,0 +1,18 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""YoloCam - Camera control application for YoloCam S3."""
__version__ = "0.1.0"
+46
View File
@@ -0,0 +1,46 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Application entry point and QApplication setup."""
import sys
import logging
from PySide6.QtWidgets import QApplication
from .ui.theme import build_stylesheet
from .ui.main_window import MainWindow
from .controller import CameraController
log = logging.getLogger(__name__)
def run():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
app = QApplication(sys.argv)
app.setApplicationName("YoloCam")
app.setStyle("Fusion")
app.setStyleSheet(build_stylesheet())
window = MainWindow()
controller = CameraController(window, parent=window)
window.set_controller(controller)
window.show()
sys.exit(app.exec())
@@ -0,0 +1,64 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""YoloCam S3 backend library for camera control over TCP protobuf."""
from .camera_client import CameraClient
from .presets import PresetManager
from yolocam.params import (
PARAMS, ParamDef, PARAM_CATEGORIES,
ISO_VALUES, SHUTTER_TABLE, SHUTTER_REVERSE, APERTURE_TABLE,
ZOOM_RAW_MIN, ZOOM_RAW_MAX, ZOOM_MULT_MIN, ZOOM_MULT_MAX,
zoom_raw_to_mult, zoom_mult_to_raw,
sharpness_to_wire, sharpness_from_wire,
format_value, format_shutter, format_aperture, format_zoom,
is_readable, is_writable,
)
from yolocam.protocol import (
CAMERA_IP, CAMERA_PORT, DEFAULT_TIMEOUT,
pack_frame, unpack_frame, xor_checksum,
)
__all__ = [
"CameraClient",
"PresetManager",
"PARAMS",
"ParamDef",
"PARAM_CATEGORIES",
"ISO_VALUES",
"SHUTTER_TABLE",
"SHUTTER_REVERSE",
"APERTURE_TABLE",
"ZOOM_RAW_MIN",
"ZOOM_RAW_MAX",
"ZOOM_MULT_MIN",
"ZOOM_MULT_MAX",
"zoom_raw_to_mult",
"zoom_mult_to_raw",
"sharpness_to_wire",
"sharpness_from_wire",
"format_value",
"format_shutter",
"format_aperture",
"format_zoom",
"is_readable",
"is_writable",
"CAMERA_IP",
"CAMERA_PORT",
"DEFAULT_TIMEOUT",
"pack_frame",
"unpack_frame",
"xor_checksum",
]
@@ -0,0 +1,61 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Qt-integrated camera client for the YoloCam S3.
Thin wrapper around YoloCamClient that emits PySide6 signals for GUI integration.
"""
from PySide6.QtCore import QObject, Signal
from yolocam.client import YoloCamClient
from yolocam.protocol import CAMERA_IP, CAMERA_PORT, DEFAULT_TIMEOUT
class CameraClient(QObject, YoloCamClient):
"""Camera client with Qt signal integration.
Overrides YoloCamClient hook methods to emit signals, allowing GUI widgets
to receive updates via Qt's signal/slot mechanism.
"""
camera_connected = Signal()
camera_disconnected = Signal()
param_changed = Signal(str, object)
error_occurred = Signal(str)
recording_state_changed = Signal(bool)
recording_duration_changed = Signal(int)
def __init__(self, ip=CAMERA_IP, port=CAMERA_PORT, timeout=DEFAULT_TIMEOUT, parent=None):
QObject.__init__(self, parent)
YoloCamClient.__init__(self, ip, port, timeout)
def _on_connected(self):
self.camera_connected.emit()
def _on_disconnected(self):
self.camera_disconnected.emit()
def _on_error(self, message):
self.error_occurred.emit(message)
def _on_param_changed(self, name, value):
self.param_changed.emit(name, value)
def _on_recording_state_changed(self, recording):
self.recording_state_changed.emit(recording)
def _on_recording_duration_changed(self, duration):
self.recording_duration_changed.emit(duration)
+176
View File
@@ -0,0 +1,176 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Preset management for YoloCam S3 camera settings.
Presets are stored as JSON files in ~/.config/yolocam-gui/presets/.
Each preset is a dict mapping parameter names to raw protocol values.
"""
import json
import logging
import os
from pathlib import Path
from typing import Any, Dict, List, Optional
from yolocam.params import PARAMS, is_readable, is_writable
log = logging.getLogger(__name__)
PRESETS_DIR = Path(os.path.expanduser("~/.config/yolocam-gui/presets"))
# Parameters to include in presets (readable + writable, skip device info and set-only)
PRESET_PARAMS = [
name for name, pdef in PARAMS.items()
if is_readable(pdef) and is_writable(pdef)
]
DEFAULT_PRESET: Dict[str, int] = {
"brightness": 50,
"sharpness": 0,
"contrast": 50,
"saturation": 50,
"hue": 50,
"gamma": 50,
"zoom": 50,
"exposure-mode": 0,
"exposure-ev": 8,
"exposure-iso": 400,
"exposure-time": 16666,
"exposure-aperture": 10,
"exposure-lock": 0,
"anti-flicker": 0,
"dynamic-range": 50,
"hdr": 0,
"wb-mode": 1,
"wb-temp": 5500,
"wb-temp-shift": 64,
"wb-lock": 0,
"focus-mode": 1,
"focus-level": 0,
"focus-caf": 0,
"distortion": 0,
"shading": 0,
"au-volume": 50,
"au-denoise": 0,
"au-gain": 0,
}
class PresetManager:
"""Save, load, and apply camera parameter presets."""
def __init__(self, presets_dir: Optional[Path] = None):
self._dir = presets_dir or PRESETS_DIR
self._dir.mkdir(parents=True, exist_ok=True)
def _preset_path(self, name: str) -> Path:
safe_name = "".join(c if c.isalnum() or c in "-_ " else "_" for c in name)
return self._dir / f"{safe_name}.json"
def list_presets(self) -> List[str]:
"""Return sorted list of saved preset names."""
names = []
for p in self._dir.glob("*.json"):
try:
data = json.loads(p.read_text())
names.append(data.get("name", p.stem))
except (json.JSONDecodeError, OSError):
continue
return sorted(names)
def save_preset(self, name: str, params: Dict[str, Any]) -> None:
"""Save a preset to disk."""
data = {"name": name, "params": params}
path = self._preset_path(name)
path.write_text(json.dumps(data, indent=2))
log.info("Saved preset '%s' to %s", name, path)
def load_preset(self, name: str) -> Optional[Dict[str, Any]]:
"""Load a preset by name. Returns the params dict or None."""
path = self._preset_path(name)
if not path.exists():
log.warning("Preset '%s' not found at %s", name, path)
return None
try:
data = json.loads(path.read_text())
return data.get("params", {})
except (json.JSONDecodeError, OSError) as exc:
log.error("Failed to load preset '%s': %s", name, exc)
return None
def delete_preset(self, name: str) -> bool:
"""Delete a saved preset. Returns True if deleted."""
path = self._preset_path(name)
if not path.exists():
return False
path.unlink()
log.info("Deleted preset '%s'", name)
return True
def get_current_state(self, client: Any) -> Dict[str, Any]:
"""Read all preset-eligible parameters from the camera.
The client argument is a CameraClient instance (import avoided to prevent circular deps).
"""
state: Dict[str, Any] = {}
for name in PRESET_PARAMS:
raw = client.get_param_raw(name)
if raw is not None:
state[name] = raw
return state
def apply_preset(self, client: Any, name: str) -> bool:
"""Load a preset and apply all its parameters to the camera.
Returns True if the preset was found and applied (individual param
failures are logged but do not fail the overall operation).
"""
params = self.load_preset(name)
if params is None:
if name == "Default":
params = DEFAULT_PRESET
else:
return False
success_count = 0
total = len(params)
for param_name, value in params.items():
if param_name not in PARAMS:
log.warning("Skipping unknown parameter in preset: %s", param_name)
continue
if client.set_param(param_name, value):
success_count += 1
else:
log.warning("Failed to set %s=%s from preset '%s'", param_name, value, name)
log.info("Applied preset '%s': %d/%d parameters set", name, success_count, total)
return True
def save_default(self) -> None:
"""Write the built-in Default preset to disk."""
self.save_preset("Default", DEFAULT_PRESET)
+608
View File
@@ -0,0 +1,608 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Controller that wires UI signals to the CameraClient backend.
Handles value conversions (zoom mult/raw, sharpness wire format, WB mode inversion),
the initialization sequence, preset management, and all panel interactions.
All background threads marshal UI updates through _ui_update (Signal) to ensure
widget manipulation only happens on the main thread.
"""
import logging
import threading
from typing import Any, Optional
from PySide6.QtCore import QObject, Signal, Slot
from .backend.camera_client import CameraClient
from yolocam.params import (
zoom_mult_to_raw, zoom_raw_to_mult,
sharpness_to_wire, sharpness_from_wire,
)
from .backend.presets import PresetManager
log = logging.getLogger(__name__)
INIT_PARAMS = [
"sharpness", "contrast", "saturation",
"exposure-mode", "shading",
"zoom",
"wb-mode", "wb-temp", "wb-temp-shift", "wb-lock",
"exposure-ev", "anti-flicker", "exposure-iso", "exposure-time", "exposure-lock",
"dynamic-range",
"focus-mode", "focus-level", "focus-caf", "focus-trigger",
"hdr",
"hue", "brightness",
"clut-attr",
]
INIT_AUDIO_PARAMS = [
"au-volume", "au-denoise", "au-gain", "au-delay", "au-reverb",
]
INIT_STREAM_PARAMS = [
"hdmi-format", "hdmi-color",
]
class CameraController(QObject):
"""Connects all panel UI signals to the CameraClient and manages initialization."""
connection_changed = Signal(str)
status_message = Signal(str)
_ui_update = Signal(str, object)
_presets_refreshed = Signal(list)
def __init__(self, window, parent: Optional[QObject] = None):
super().__init__(parent)
self._window = window
self._panel = window.params_panel
self._color_panel = window.color_panel
self._console_panel = window.console_panel
self._stream_panel = window.stream_panel
self._settings_panel = window.settings_panel
self._client = CameraClient(parent=self)
self._presets = PresetManager()
self._connected = False
self._wb_red_offset = 10
self._wb_blue_offset = 10
self._tuning_brightness = 50
self._tuning_color_temp = 5500
self._ui_update.connect(self._update_ui_widget)
self._presets_refreshed.connect(self._panel.preset_bar.set_presets)
self._client.camera_connected.connect(self._on_connected)
self._client.camera_disconnected.connect(self._on_disconnected)
self._client.error_occurred.connect(self._on_error)
self._client.recording_state_changed.connect(self._console_panel.set_recording_state)
self._client.recording_duration_changed.connect(self._console_panel.set_recording_duration)
self._panel.param_changed.connect(self._on_param_changed)
self._panel.refresh_requested.connect(self.refresh_all)
self._panel.save_scene_requested.connect(self._on_save_scene)
self._panel.preset_bar.preset_selected.connect(self._on_preset_selected)
self._panel.preset_bar.preset_deleted.connect(self._on_preset_deleted)
self._panel.white_balance.eyedropper_requested.connect(self._on_eyedropper_requested)
self._window.video_widget.color_sampled.connect(self._on_color_sampled)
self._window.video_widget.eyedropper_deactivated.connect(
lambda: self._panel.white_balance.set_eyedropper_active(False)
)
self._color_panel.param_changed.connect(self._on_param_changed)
self._console_panel.param_changed.connect(self._on_param_changed)
self._stream_panel.param_changed.connect(self._on_param_changed)
self._settings_panel.format_sd_requested.connect(self._on_format_sd)
self._refresh_presets()
@property
def client(self) -> CameraClient:
return self._client
def connect_camera(self):
"""Initiate connection to camera in a background thread."""
self.status_message.emit("Connecting...")
def _connect():
try:
self._client.open()
except Exception as exc:
log.error("Connection failed: %s", exc)
threading.Thread(target=_connect, daemon=True, name="camera-connect").start()
def disconnect_camera(self):
self._client.close()
@Slot()
def refresh_all(self):
"""Read all parameters from camera and update UI."""
if not self._connected:
self.status_message.emit("Not connected")
return
self.status_message.emit("Reading parameters...")
def _read():
self._read_init_params()
self._read_audio_params()
self._read_stream_params()
self._read_wb_offset()
self._read_device_info()
self.status_message.emit("Ready")
threading.Thread(target=_read, daemon=True, name="param-refresh").start()
def _on_connected(self):
self._connected = True
self.connection_changed.emit("connected")
self.status_message.emit("Connected")
self._update_camera_combo("Y-CAM (connected)")
self._window.video_widget.auto_start()
self.refresh_all()
def _on_disconnected(self):
self._connected = False
self.connection_changed.emit("disconnected")
self.status_message.emit("Disconnected")
self._update_camera_combo("Y-CAM (disconnected)")
def _on_error(self, msg: str):
log.error("Camera error: %s", msg)
self.status_message.emit(f"Error: {msg}")
def _update_camera_combo(self, text: str):
combo = self._panel.camera_combo
combo.blockSignals(True)
combo.clear()
combo.addItem(text)
combo.blockSignals(False)
@Slot(str, object)
def _on_param_changed(self, name: str, value: Any):
"""Handle a UI parameter change by sending it to the camera."""
if not self._connected:
return
if name == "recording-start":
self._do_recording(True)
return
if name == "recording-stop":
self._do_recording(False)
return
if name == "ai-tracking":
self._do_ai_tracking(int(value))
return
if name == "clut-enable":
self._do_clut_enable(bool(value))
return
if name == "clut-attr":
self._do_clut_attr(int(value))
return
if name == "clut-reset":
self._do_clut_reset()
return
if name == "clut-grid-changed":
self._do_clut_grid(value)
return
if name == "wb-blue-offset":
self._wb_blue_offset = int(value)
self._do_wb_offset()
return
if name == "wb-red-offset":
self._wb_red_offset = int(value)
self._do_wb_offset()
return
if name == "color-hue":
wire_val = int(round(int(value) * 100.0 / 360.0))
self._send_param("hue", wire_val)
return
if name == "color-saturation":
self._send_param("saturation", int(value))
return
if name == "color-brightness":
self._send_param("brightness", int(value))
return
if name == "tuning-brightness":
self._tuning_brightness = int(value)
self._do_tuning()
return
if name == "tuning-color-temp":
self._tuning_color_temp = int(value)
self._do_tuning()
return
wire_value = self._ui_to_wire(name, value)
log.debug("UI -> camera: %s = %r (wire: %r)", name, value, wire_value)
def _send():
success = self._client.set_param(name, wire_value)
if not success:
log.warning("Failed to set %s=%r", name, wire_value)
threading.Thread(target=_send, daemon=True, name=f"set-{name}").start()
def _send_param(self, name: str, wire_value: Any):
"""Send a raw wire value to the camera in a background thread."""
if not self._connected:
return
def _send():
self._client.set_param(name, wire_value)
threading.Thread(target=_send, daemon=True, name=f"set-{name}").start()
def _do_recording(self, start: bool):
def _run():
if start:
success = self._client.start_recording()
else:
success = self._client.stop_recording()
if not success:
log.warning("Recording %s failed", "start" if start else "stop")
self._client.recording_state_changed.emit(not start)
threading.Thread(target=_run, daemon=True, name="recording").start()
def _do_ai_tracking(self, mode: int):
def _run():
self._client.set_ai_tracking(mode)
threading.Thread(target=_run, daemon=True, name="ai-tracking").start()
def _do_clut_enable(self, enabled: bool):
def _run():
self._client.set_clut_enabled(enabled)
threading.Thread(target=_run, daemon=True, name="clut-enable").start()
def _do_clut_attr(self, value: int):
def _run():
self._client.set_clut_attr(value)
threading.Thread(target=_run, daemon=True, name="clut-attr").start()
def _do_clut_reset(self):
def _run():
self._client.reset_clut()
self._client.set_clut_attr(0)
self._ui_update.emit("clut-attr", 0)
threading.Thread(target=_run, daemon=True, name="clut-reset").start()
def _do_clut_grid(self, grid_data: dict):
def _run():
if grid_data.get("mode") == "fast":
from yolocam.clut import fast_grid_to_clut
clut = fast_grid_to_clut(grid_data["grid"], grid_data.get("luma"))
else:
from yolocam.clut import hsv_grid_to_clut, LUMA_LEVELS, SAT_COLUMNS, HUE_SECTORS
wheel_hue = grid_data.get("hue", [])
wheel_sat = grid_data.get("sat", [])
wheel_luma = grid_data.get("luma", [])
n_hue = HUE_SECTORS + 1
hue_grid = [[[0.0] * n_hue for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
sat_grid = [[[1.0] * n_hue for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
luma_grid = [[[0.0] * n_hue for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
for h in range(min(n_hue, len(wheel_hue))):
for s in range(min(SAT_COLUMNS, len(wheel_hue[h]) if h < len(wheel_hue) else 0)):
hv = wheel_hue[h][s] if h < len(wheel_hue) and s < len(wheel_hue[h]) else 0.0
sv = wheel_sat[h][s] if h < len(wheel_sat) and s < len(wheel_sat[h]) else 0.0
lv = wheel_luma[h][s] if h < len(wheel_luma) and s < len(wheel_luma[h]) else 0.0
sat_scale = 1.0 + sv / 100.0
for l in range(LUMA_LEVELS):
hue_grid[l][s][h] = hv
sat_grid[l][s][h] = sat_scale
luma_grid[l][s][h] = lv / 100.0
clut = hsv_grid_to_clut(hue_grid, sat_grid, luma_grid)
self._client.send_clut(clut, hsv_data="{}")
self._client.set_clut_attr(0)
threading.Thread(target=_run, daemon=True, name="clut-grid").start()
def _on_eyedropper_requested(self):
self._window.video_widget.set_eyedropper_mode(True)
def _on_color_sampled(self, r: int, g: int, b: int):
self._panel.white_balance.set_eyedropper_active(False)
from yolocam.color import rgb_to_cct
temp = rgb_to_cct(r, g, b)
self._ui_update.emit("wb-mode", 0)
self._ui_update.emit("wb-temp", temp)
self.status_message.emit(f"WB: {temp}K from RGB({r},{g},{b})")
def _apply():
self._client.set_param("wb-mode", 0)
self._client.set_param("wb-temp", temp)
threading.Thread(target=_apply, daemon=True, name="eyedropper-wb").start()
def _do_wb_offset(self):
def _run():
self._client.set_wb_offset(self._wb_red_offset, self._wb_blue_offset)
threading.Thread(target=_run, daemon=True, name="wb-offset").start()
def _do_tuning(self):
def _run():
self._client.set_tuning(self._tuning_brightness, 0, self._tuning_color_temp)
threading.Thread(target=_run, daemon=True, name="tuning").start()
def _on_format_sd(self):
def _run():
self.status_message.emit("Formatting SD card...")
success = self._client.format_sd_card()
if success:
self.status_message.emit("SD card formatted")
else:
self.status_message.emit("SD card format failed")
threading.Thread(target=_run, daemon=True, name="format-sd").start()
def _ui_to_wire(self, name: str, value: Any) -> Any:
"""Convert UI-facing values to wire protocol values.
Note: zoom is NOT converted here because set_param() already handles
the multiplier-to-raw conversion internally.
"""
if name == "sharpness":
return sharpness_to_wire(int(value))
if name == "wb-mode":
return int(value)
if name in ("shading", "hdr", "exposure-lock", "wb-lock", "focus-caf", "au-gain", "uvc"):
return 1 if value else 0
if name == "zoom":
return float(value)
return int(value)
def _wire_to_ui(self, name: str, raw: int) -> Any:
"""Convert wire protocol values to UI-facing values."""
if name == "zoom":
return zoom_raw_to_mult(raw)
if name == "sharpness":
return sharpness_from_wire(raw)
return raw
def _read_init_params(self):
"""Read initialization parameters and emit UI updates via signal."""
for name in INIT_PARAMS:
raw = self._client.get_param_raw(name)
if raw is None:
continue
ui_val = self._wire_to_ui(name, raw)
self._ui_update.emit(name, ui_val)
def _read_audio_params(self):
"""Read audio parameters and emit UI updates via signal."""
for name in INIT_AUDIO_PARAMS:
raw = self._client.get_param_raw(name)
if raw is None:
continue
self._ui_update.emit(name, raw)
def _read_stream_params(self):
"""Read stream/HDMI parameters and emit UI updates via signal."""
for name in INIT_STREAM_PARAMS:
raw = self._client.get_param_raw(name)
if raw is None:
continue
self._ui_update.emit(name, raw)
def _read_wb_offset(self):
"""Read WB offset compound message and cache the values."""
from yolocam import yolocam_pb2 as pb
resp = self._client.request(pb.CID_WHITE_BALANCE_OFFSET)
if resp is None or not resp.HasField("body"):
return
body = resp.body
if body.WhichOneof("value") == "white_balance_offset":
self._wb_red_offset = body.white_balance_offset.offset_r
self._wb_blue_offset = body.white_balance_offset.offset_b
self._ui_update.emit("wb-red-offset-display", self._wb_red_offset)
self._ui_update.emit("wb-blue-offset-display", self._wb_blue_offset)
def _read_device_info(self):
"""Read device info and emit UI updates via signal."""
version_str = self._client.get_param("version")
if version_str:
self._ui_update.emit("device-firmware", version_str)
lens_str = self._client.get_param("lens-detail")
if lens_str:
self._ui_update.emit("device-lens", lens_str)
@Slot(str, object)
def _update_ui_widget(self, name: str, value: Any):
"""Route a parameter value to the appropriate UI widget setter.
Always runs on the main thread via the _ui_update signal connection.
"""
p = self._panel
if name == "sharpness":
p.image.set_sharpness(int(value))
elif name == "contrast":
p.image.set_contrast(int(value))
elif name == "saturation":
p.image.set_saturation(int(value))
self._color_panel.set_saturation(int(value))
elif name == "dynamic-range":
p.image.set_dynamic_range(int(value))
elif name == "frame-rate":
p.graphics.set_frame_rate(int(value))
elif name == "shading":
p.graphics.set_shading(bool(value))
elif name == "zoom":
p.zoom.set_zoom(float(value))
self._console_panel.set_zoom(float(value))
elif name == "focus-mode":
p.focus.set_focus_mode(int(value))
elif name == "focus-level":
p.focus.set_focus_area(int(value))
elif name == "focus-caf":
p.focus.set_focus_power(bool(value))
elif name == "focus-trigger":
p.focus.set_focus_speed(int(value))
elif name == "exposure-mode":
p.exposure.set_exposure_mode(int(value))
elif name == "hdr":
p.exposure.set_hdr(bool(value))
elif name == "anti-flicker":
p.exposure.set_anti_flicker(int(value))
elif name == "exposure-ev":
p.exposure.set_ev(int(value))
elif name == "exposure-iso":
p.exposure.set_iso(int(value))
elif name == "exposure-time":
p.exposure.set_shutter(int(value))
elif name == "exposure-lock":
p.exposure.set_exposure_lock(bool(value))
elif name == "wb-mode":
p.white_balance.set_wb_mode(int(value))
elif name == "wb-temp":
p.white_balance.set_temperature(int(value))
elif name == "wb-temp-shift":
p.white_balance.set_temp_shift(int(value))
elif name == "wb-lock":
p.white_balance.set_wb_lock(bool(value))
elif name == "au-volume":
p.audio.set_volume(int(value))
elif name == "au-denoise":
p.audio.set_noise_reduction(int(value))
elif name == "au-delay":
p.audio.set_delay(int(value))
elif name == "au-gain":
p.audio.set_auto_gain(bool(value))
elif name == "au-reverb":
p.audio.set_reverb(int(value))
elif name == "hue":
hue_360 = int(round(int(value) * 360.0 / 100.0))
self._color_panel.set_hue(hue_360)
elif name == "brightness":
self._color_panel.set_brightness(int(value))
elif name == "hdmi-format":
self._stream_panel.set_hdmi_format(int(value))
elif name == "hdmi-color":
self._stream_panel.set_hdmi_color(int(value))
elif name == "wb-red-offset-display":
p.white_balance.set_red_offset(int(value))
elif name == "wb-blue-offset-display":
p.white_balance.set_blue_offset(int(value))
elif name == "device-firmware":
self._settings_panel.set_firmware_info(str(value))
elif name == "device-lens":
self._settings_panel.set_lens_info(str(value))
elif name == "clut-attr":
self._color_panel.set_clut_attr(int(value))
elif name == "device-disk":
self._settings_panel.set_disk_info(value[0], value[1])
def _on_save_scene(self):
"""Save current camera state as a preset."""
if not self._connected:
self.status_message.emit("Connect to camera first")
return
from PySide6.QtWidgets import QInputDialog
name, ok = QInputDialog.getText(
self._panel, "Save Preset", "Preset name:"
)
if not ok or not name:
return
self.status_message.emit(f"Saving preset '{name}'...")
def _save():
state = self._presets.get_current_state(self._client)
self._presets.save_preset(name, state)
self._presets_refreshed.emit(self._presets.list_presets())
self.status_message.emit(f"Preset '{name}' saved")
threading.Thread(target=_save, daemon=True, name="save-preset").start()
def _on_preset_selected(self, name: str):
"""Apply a preset to the camera."""
if not self._connected:
self.status_message.emit("Connect to camera first")
return
self.status_message.emit(f"Applying preset '{name}'...")
def _apply():
self._presets.apply_preset(self._client, name)
self._read_init_params()
self._read_audio_params()
self.status_message.emit(f"Preset '{name}' applied")
threading.Thread(target=_apply, daemon=True, name="apply-preset").start()
def _on_preset_deleted(self, name: str):
"""Delete a preset."""
self._presets.delete_preset(name)
self._refresh_presets()
def _refresh_presets(self):
names = self._presets.list_presets()
self._panel.preset_bar.set_presets(names)
+15
View File
@@ -0,0 +1,15 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
+164
View File
@@ -0,0 +1,164 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Main application window."""
import logging
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QKeySequence, QShortcut
from PySide6.QtWidgets import (
QMainWindow, QWidget, QHBoxLayout, QScrollArea, QStackedWidget, QSizePolicy,
)
from .theme import COLOR_BG_PANEL, COLOR_BORDER
from .sidebar import Sidebar
from .video_widget import VideoWidget
from .panels import ImageParamsPanel, ColorPanel, ConsolePanel, StreamPanel, SettingsPanel
log = logging.getLogger(__name__)
class MainWindow(QMainWindow):
"""YoloCam main window with sidebar, stacked panels, and video feed."""
def __init__(self):
super().__init__()
self.setWindowTitle("YoloCam")
self.resize(1100, 570)
self._build_menu_bar()
self.statusBar().showMessage("Disconnected")
central = QWidget()
self.setCentralWidget(central)
root_layout = QHBoxLayout(central)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setSpacing(0)
self.sidebar = Sidebar()
self.sidebar.page_changed.connect(self._on_page_changed)
root_layout.addWidget(self.sidebar)
self.params_panel = ImageParamsPanel()
self.color_panel = ColorPanel()
self.console_panel = ConsolePanel()
self.stream_panel = StreamPanel()
self.settings_panel = SettingsPanel()
self._stacked = QStackedWidget()
self._panels = [
self.params_panel,
self.color_panel,
self.console_panel,
self.stream_panel,
self.settings_panel,
]
for panel in self._panels:
scroll = QScrollArea()
scroll.setWidget(panel)
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
scroll.setStyleSheet(f"""
QScrollArea {{ border-right: 1px solid {COLOR_BORDER}; background-color: {COLOR_BG_PANEL}; }}
""")
self._stacked.addWidget(scroll)
self._stacked.setFixedWidth(400)
root_layout.addWidget(self._stacked)
self.video_widget = VideoWidget(device_index=-1)
self.video_widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
root_layout.addWidget(self.video_widget, 1)
self._controller = None
def set_controller(self, controller):
"""Attach the CameraController after construction."""
self._controller = controller
controller.status_message.connect(self.statusBar().showMessage)
controller.connection_changed.connect(self._on_connection_changed)
QTimer.singleShot(500, controller.connect_camera)
def _build_menu_bar(self):
menu_bar = self.menuBar()
app_menu = menu_bar.addMenu("YoloCam")
self._connect_action = app_menu.addAction("Connect to Camera")
self._connect_action.setShortcut(QKeySequence("Ctrl+Shift+C"))
self._connect_action.triggered.connect(self._toggle_connection)
app_menu.addSeparator()
quit_action = app_menu.addAction("Quit")
quit_action.setShortcut(QKeySequence.StandardKey.Quit)
quit_action.triggered.connect(self.close)
view_menu = menu_bar.addMenu("View")
for i, (label, key) in enumerate([
("Camera", "1"), ("Color", "2"), ("Console", "3"),
("Stream", "4"), ("Settings", "5"),
]):
action = view_menu.addAction(label)
action.setShortcut(QKeySequence(f"Ctrl+{key}"))
action.triggered.connect(lambda checked, idx=i: self._switch_panel(idx))
view_menu.addSeparator()
fullscreen_action = view_menu.addAction("Toggle Fullscreen")
fullscreen_action.setShortcut(QKeySequence.StandardKey.FullScreen)
fullscreen_action.triggered.connect(self._toggle_fullscreen)
help_menu = menu_bar.addMenu("Help")
help_menu.addAction("Documentation")
def _switch_panel(self, index: int):
if 0 <= index < self._stacked.count():
self._stacked.setCurrentIndex(index)
self.sidebar.set_active(index)
def _toggle_fullscreen(self):
if self.isFullScreen():
self.showNormal()
else:
self.showFullScreen()
def _on_page_changed(self, index: int):
if 0 <= index < self._stacked.count():
self._stacked.setCurrentIndex(index)
def _toggle_connection(self):
if self._controller is None:
return
if self._controller.client.connection_state == "connected":
self._controller.disconnect_camera()
else:
self._controller.connect_camera()
def _on_connection_changed(self, state: str):
if state == "connected":
self._connect_action.setText("Disconnect")
else:
self._connect_action.setText("Connect to Camera")
def closeEvent(self, event):
if self._controller:
self._controller.disconnect_camera()
self.video_widget.stop()
super().closeEvent(event)
@@ -0,0 +1,28 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .image_params import ImageParamsPanel
from .color_panel import ColorPanel
from .console_panel import ConsolePanel
from .stream_panel import StreamPanel
from .settings_panel import SettingsPanel
__all__ = [
"ImageParamsPanel",
"ColorPanel",
"ConsolePanel",
"StreamPanel",
"SettingsPanel",
]
@@ -0,0 +1,106 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Audio settings section."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QComboBox
from ..widgets import CollapsibleSection, ParamSlider, ToggleSwitch
NOISE_LEVELS = ["Close", "Weak", "Middle", "Strong"]
REVERB_LEVELS = ["Close", "Weak", "Middle", "Strong"]
class AudioSection(CollapsibleSection):
"""Collapsible panel for audio settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Audio Settings", parent)
self.volume_slider = ParamSlider("Volume", min_val=0, max_val=100, default=50, step=1)
self.volume_slider.value_changed.connect(lambda v: self.param_changed.emit("au-volume", v))
self.add_widget(self.volume_slider)
self.noise_combo = QComboBox()
self.noise_combo.addItems(NOISE_LEVELS)
self.noise_combo.setCurrentIndex(2)
self.noise_combo.currentIndexChanged.connect(
lambda idx: self.param_changed.emit("au-denoise", idx)
)
self.add_widget(self._labeled("Noise Reduction", self.noise_combo))
self.delay_slider = ParamSlider("Audio Delay", min_val=0, max_val=400, default=0, step=1, suffix="ms")
self.delay_slider.value_changed.connect(lambda v: self.param_changed.emit("au-delay", v))
self.add_widget(self.delay_slider)
self.auto_gain_toggle = ToggleSwitch(checked=True)
self.auto_gain_toggle.toggled.connect(lambda v: self.param_changed.emit("au-gain", v))
self._auto_gain_row = self._toggle_row("Auto Gain", self.auto_gain_toggle)
self.add_widget(self._auto_gain_row)
self.reverb_combo = QComboBox()
self.reverb_combo.addItems(REVERB_LEVELS)
self.reverb_combo.currentIndexChanged.connect(
lambda idx: self.param_changed.emit("au-reverb", idx)
)
self.add_widget(self._labeled("Reverb", self.reverb_combo))
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def set_volume(self, value: int):
self.volume_slider.set_value(float(value), emit=False)
def set_noise_reduction(self, value: int):
self.noise_combo.blockSignals(True)
self.noise_combo.setCurrentIndex(value)
self.noise_combo.blockSignals(False)
def set_delay(self, value: int):
self.delay_slider.set_value(float(value), emit=False)
def set_auto_gain(self, enabled: bool):
self.auto_gain_toggle.set_checked(enabled, emit=False)
def set_reverb(self, value: int):
self.reverb_combo.blockSignals(True)
self.reverb_combo.setCurrentIndex(value)
self.reverb_combo.blockSignals(False)
@@ -0,0 +1,215 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Color correction panel with HSV color wheel, sliders, and CLUT controls."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QSizePolicy,
)
from PySide6.QtGui import QFont
from ..theme import COLOR_ACCENT, COLOR_BG_PANEL, COLOR_TEXT_SECONDARY
from ..widgets import CollapsibleSection, ColorWheel, ParamSlider, ToggleSwitch, SegmentButton
class ColorPanel(QWidget):
"""Panel for HSV color grading and CLUT control.
Provides a visual color wheel for hue/saturation selection,
sliders for fine control, and CLUT enable/disable toggle.
"""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("colorPanel")
self.setStyleSheet(f"#colorPanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Color")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
outer.addWidget(header)
self._mode = SegmentButton(["Fast", "Professional"])
mode_row = QWidget()
mode_layout = QHBoxLayout(mode_row)
mode_layout.setContentsMargins(12, 4, 12, 4)
mode_layout.setSpacing(8)
mode_layout.addWidget(self._mode)
outer.addWidget(mode_row)
wheel_container = QWidget()
wheel_layout = QVBoxLayout(wheel_container)
wheel_layout.setContentsMargins(0, 8, 0, 4)
wheel_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._wheel = ColorWheel()
wheel_layout.addWidget(self._wheel, 0, Qt.AlignmentFlag.AlignCenter)
self._grid_reset_btn = QPushButton("Reset Grid")
self._grid_reset_btn.setFixedHeight(28)
self._grid_reset_btn.setFixedWidth(self._wheel.WHEEL_SIZE)
wheel_layout.addWidget(self._grid_reset_btn, 0, Qt.AlignmentFlag.AlignCenter)
outer.addWidget(wheel_container)
slider_section = CollapsibleSection("HSV Controls")
self._hue_slider = ParamSlider("Hue", min_val=0, max_val=360, default=0, step=1)
slider_section.add_widget(self._hue_slider)
self._sat_slider = ParamSlider("Saturation", min_val=0, max_val=100, default=0, step=1)
slider_section.add_widget(self._sat_slider)
self._bright_slider = ParamSlider("Brightness", min_val=0, max_val=100, default=100, step=1)
slider_section.add_widget(self._bright_slider)
outer.addWidget(slider_section)
clut_section = CollapsibleSection("Color LUT")
self._clut_toggle = ToggleSwitch()
clut_section.add_widget(self._toggle_row("Enable CLUT", self._clut_toggle))
self._clut_attr = ParamSlider("Intensity", min_val=0, max_val=255, default=0, step=1)
clut_section.add_widget(self._clut_attr)
self._clut_reset_btn = QPushButton("Reset Color Grading")
self._clut_reset_btn.setProperty("accent", True)
self._clut_reset_btn.setFixedHeight(32)
clut_section.add_widget(self._clut_reset_btn)
outer.addWidget(clut_section)
tuning_section = CollapsibleSection("Tuning", expanded=False)
self._tuning_brightness = ParamSlider("Brightness", min_val=0, max_val=100, default=50, step=1)
tuning_section.add_widget(self._tuning_brightness)
self._tuning_color_temp = ParamSlider("Color Temp", min_val=2000, max_val=10000, default=5500, step=50)
tuning_section.add_widget(self._tuning_color_temp)
outer.addWidget(tuning_section)
outer.addStretch()
self._wire_signals()
def _wire_signals(self):
self._wheel.hue_changed.connect(self._on_wheel_hue)
self._wheel.saturation_changed.connect(self._on_wheel_sat)
self._hue_slider.value_changed.connect(self._on_slider_hue)
self._sat_slider.value_changed.connect(self._on_slider_sat)
self._bright_slider.value_changed.connect(self._on_slider_bright)
self._clut_toggle.toggled.connect(
lambda v: self.param_changed.emit("clut-enable", v)
)
self._clut_attr.value_changed.connect(
lambda v: self.param_changed.emit("clut-attr", int(v))
)
self._clut_reset_btn.clicked.connect(
lambda: self.param_changed.emit("clut-reset", True)
)
self._grid_reset_btn.clicked.connect(self._on_grid_reset)
self._mode.selection_changed.connect(self._on_mode_changed)
self._wheel.grid_changed.connect(
lambda data: self.param_changed.emit("clut-grid-changed", data)
)
self._tuning_brightness.value_changed.connect(
lambda v: self.param_changed.emit("tuning-brightness", v)
)
self._tuning_color_temp.value_changed.connect(
lambda v: self.param_changed.emit("tuning-color-temp", v)
)
def _on_wheel_hue(self, hue: int):
self._hue_slider.set_value(float(hue), emit=False)
self.param_changed.emit("color-hue", hue)
def _on_wheel_sat(self, sat: int):
self._sat_slider.set_value(float(sat), emit=False)
self.param_changed.emit("color-saturation", sat)
def _on_slider_hue(self, val: float):
self._wheel.set_hue(int(val))
self.param_changed.emit("color-hue", int(val))
def _on_slider_sat(self, val: float):
self._wheel.set_saturation(int(val))
self.param_changed.emit("color-saturation", int(val))
def _on_slider_bright(self, val: float):
self._wheel.set_brightness(int(val))
self.param_changed.emit("color-brightness", int(val))
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def set_hue(self, value: int):
self._wheel.set_hue(value)
self._hue_slider.set_value(float(value), emit=False)
def set_saturation(self, value: int):
self._wheel.set_saturation(value)
self._sat_slider.set_value(float(value), emit=False)
def set_brightness(self, value: int):
self._wheel.set_brightness(value)
self._bright_slider.set_value(float(value), emit=False)
def set_clut_enabled(self, enabled: bool):
self._clut_toggle.set_checked(enabled, emit=False)
def set_clut_attr(self, value: int):
self._clut_attr.set_value(float(value), emit=False)
def set_grid_data(self, data: dict):
self._wheel.set_grid_data(data)
def _on_grid_reset(self):
self._wheel.reset_grid()
self.param_changed.emit("clut-reset", True)
def _on_mode_changed(self, index: int):
mode = "fast" if index == 0 else "professional"
self._wheel.set_mode(mode)
@@ -0,0 +1,306 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Console panel with recording, AI tracking, and zoom controls."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
)
from PySide6.QtGui import QFont, QPainter, QColor
from ..theme import (
COLOR_ACCENT, COLOR_BG_PANEL, COLOR_BG_INPUT, COLOR_BORDER,
COLOR_TEXT_PRIMARY, COLOR_TEXT_SECONDARY,
)
from ..widgets import CollapsibleSection, SegmentButton
AI_TRACKING_MAP = {0: 2, 1: 0, 2: 1}
class _RecordButton(QPushButton):
"""Circular record button that toggles between ready and recording states."""
def __init__(self, parent=None):
super().__init__(parent)
self._recording = False
self.setFixedSize(60, 60)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setStyleSheet("QPushButton { background: transparent; border: none; }")
@property
def recording(self) -> bool:
return self._recording
@recording.setter
def recording(self, value: bool):
self._recording = value
self.update()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(COLOR_ACCENT))
p.drawEllipse(2, 2, 56, 56)
p.setBrush(QColor(COLOR_TEXT_PRIMARY))
if self._recording:
# White square (stop icon)
p.drawRoundedRect(20, 20, 20, 20, 3, 3)
else:
# White circle (record icon)
p.drawEllipse(17, 17, 26, 26)
p.end()
class _RecordingSection(CollapsibleSection):
"""Recording controls with record button, duration, and status."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Recording", parent)
self._recording = False
btn_container = QWidget()
btn_layout = QVBoxLayout(btn_container)
btn_layout.setContentsMargins(0, 4, 0, 4)
btn_layout.setSpacing(6)
btn_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.record_btn = _RecordButton()
self.record_btn.clicked.connect(self._toggle_recording)
btn_layout.addWidget(self.record_btn, 0, Qt.AlignmentFlag.AlignCenter)
self.duration_label = QLabel("00:00:00")
duration_font = QFont("monospace", 14)
self.duration_label.setFont(duration_font)
self.duration_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
btn_layout.addWidget(self.duration_label)
self.status_label = QLabel("Ready")
self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.status_label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
btn_layout.addWidget(self.status_label)
self.add_widget(btn_container)
def _toggle_recording(self):
self._recording = not self._recording
self.record_btn.recording = self._recording
if self._recording:
self.status_label.setText("Recording")
self.status_label.setStyleSheet(f"color: {COLOR_ACCENT};")
self.param_changed.emit("recording-start", True)
else:
self.status_label.setText("Ready")
self.status_label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
self.param_changed.emit("recording-stop", True)
def set_recording_state(self, recording: bool):
self._recording = recording
self.record_btn.recording = recording
if recording:
self.status_label.setText("Recording")
self.status_label.setStyleSheet(f"color: {COLOR_ACCENT};")
else:
self.status_label.setText("Ready")
self.status_label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
self.duration_label.setText("00:00:00")
def set_recording_duration(self, seconds: int):
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
self.duration_label.setText(f"{h:02d}:{m:02d}:{s:02d}")
class _AITrackingSection(CollapsibleSection):
"""AI tracking mode selection."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("AI Tracking", parent)
self.mode_btn = SegmentButton(["Off", "Portrait", "Thing"])
self.mode_btn.selection_changed.connect(self._mode_changed)
self.add_widget(self._labeled("Mode", self.mode_btn))
def _mode_changed(self, index: int):
self.param_changed.emit("ai-tracking", AI_TRACKING_MAP[index])
def set_ai_tracking_mode(self, wire_value: int):
"""Set mode by wire protocol value (0=Portrait, 1=Thing, 2=Close)."""
reverse_map = {2: 0, 0: 1, 1: 2}
ui_index = reverse_map.get(wire_value, 0)
self.mode_btn.set_selected(ui_index, emit=False)
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
class _ZoomSection(CollapsibleSection):
"""Zoom controls with +/- buttons and quick presets."""
ZOOM_MIN = 1.0
ZOOM_MAX = 4.0
ZOOM_STEP = 0.5
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Zoom Controls", parent)
self._zoom = 1.0
self.zoom_display = QLabel("1.0x")
display_font = QFont()
display_font.setPointSize(18)
display_font.setBold(True)
self.zoom_display.setFont(display_font)
self.zoom_display.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.add_widget(self.zoom_display)
step_row = QWidget()
step_layout = QHBoxLayout(step_row)
step_layout.setContentsMargins(0, 4, 0, 4)
step_layout.setSpacing(8)
step_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.zoom_minus = QPushButton("\u2212")
self.zoom_minus.setFixedSize(40, 40)
self.zoom_minus.setCursor(Qt.CursorShape.PointingHandCursor)
self.zoom_minus.setStyleSheet(f"""
QPushButton {{ font-size: 20px; font-weight: bold; background-color: {COLOR_BG_INPUT};
border: 1px solid {COLOR_BORDER}; border-radius: 20px; }}
QPushButton:hover {{ background-color: {COLOR_BORDER}; }}
""")
self.zoom_minus.clicked.connect(self._zoom_out)
step_layout.addWidget(self.zoom_minus)
self.zoom_plus = QPushButton("+")
self.zoom_plus.setFixedSize(40, 40)
self.zoom_plus.setCursor(Qt.CursorShape.PointingHandCursor)
self.zoom_plus.setStyleSheet(f"""
QPushButton {{ font-size: 20px; font-weight: bold; background-color: {COLOR_BG_INPUT};
border: 1px solid {COLOR_BORDER}; border-radius: 20px; }}
QPushButton:hover {{ background-color: {COLOR_BORDER}; }}
""")
self.zoom_plus.clicked.connect(self._zoom_in)
step_layout.addWidget(self.zoom_plus)
self.add_widget(step_row)
preset_row = QWidget()
preset_layout = QHBoxLayout(preset_row)
preset_layout.setContentsMargins(0, 2, 0, 2)
preset_layout.setSpacing(6)
for zoom_val in [1.0, 2.0, 3.0, 4.0]:
btn = QPushButton(f"{int(zoom_val)}x")
btn.setFixedSize(48, 28)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.clicked.connect(lambda checked, v=zoom_val: self._preset_clicked(v))
preset_layout.addWidget(btn)
preset_layout.addStretch()
self.add_widget(preset_row)
def _apply_zoom(self, value: float):
self._zoom = max(self.ZOOM_MIN, min(self.ZOOM_MAX, round(value, 1)))
self.zoom_display.setText(f"{self._zoom:.1f}x")
self.param_changed.emit("zoom", self._zoom)
def _zoom_in(self):
self._apply_zoom(self._zoom + self.ZOOM_STEP)
def _zoom_out(self):
self._apply_zoom(self._zoom - self.ZOOM_STEP)
def _preset_clicked(self, value: float):
self._apply_zoom(value)
def set_zoom(self, value: float):
self._zoom = max(self.ZOOM_MIN, min(self.ZOOM_MAX, round(value, 1)))
self.zoom_display.setText(f"{self._zoom:.1f}x")
class ConsolePanel(QWidget):
"""Panel with recording, AI tracking, and zoom controls."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("consolePanel")
self.setStyleSheet(f"#consolePanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Console")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
outer.addWidget(header)
self.recording = _RecordingSection()
self.ai_tracking = _AITrackingSection()
self.zoom = _ZoomSection()
for section in [self.recording, self.ai_tracking, self.zoom]:
section.param_changed.connect(self.param_changed.emit)
outer.addWidget(section)
outer.addStretch()
def set_recording_state(self, recording: bool):
self.recording.set_recording_state(recording)
def set_recording_duration(self, seconds: int):
self.recording.set_recording_duration(seconds)
def set_zoom(self, value: float):
self.zoom.set_zoom(value)
def set_ai_tracking_mode(self, wire_value: int):
self.ai_tracking.set_ai_tracking_mode(wire_value)
@@ -0,0 +1,182 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Exposure settings section with mode-dependent controls."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QComboBox
from ..widgets import CollapsibleSection, SegmentButton, ParamSlider, ToggleSwitch
S3_ISO_VALUES = [
100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250,
1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 9600, 12800,
]
SHUTTER_LABELS = [
("1/25", 40000), ("1/30", 33333), ("1/50", 20000), ("1/60", 16666),
("1/80", 12500), ("1/100", 10000), ("1/125", 8000), ("1/160", 6250),
("1/200", 5000), ("1/250", 4000), ("1/320", 3125), ("1/400", 2500),
("1/500", 2000), ("1/640", 1562), ("1/800", 1250), ("1/1000", 1000),
("1/1250", 800), ("1/1600", 625), ("1/2000", 500), ("1/2500", 400),
("1/3200", 312), ("1/4000", 250), ("1/5000", 200), ("1/6400", 156),
("1/8000", 125),
]
EV_LABELS = [
"-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1",
"0", "+1", "+2", "+3", "+4", "+5", "+6", "+7", "+8",
]
class ExposureSection(CollapsibleSection):
"""Collapsible panel for exposure with auto/manual mode switching."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Exposure", parent)
self.exposure_mode = SegmentButton(["Auto", "Manual"])
self.exposure_mode.selection_changed.connect(self._mode_changed)
self.add_widget(self._labeled("Mode", self.exposure_mode))
self.hdr_toggle = ToggleSwitch()
self.hdr_toggle.toggled.connect(lambda v: self.param_changed.emit("hdr", v))
self._hdr_row = self._toggle_row("HDR", self.hdr_toggle)
self.add_widget(self._hdr_row)
self.anti_flicker = SegmentButton(["Close", "50Hz", "60Hz"])
self.anti_flicker.selection_changed.connect(
lambda idx: self.param_changed.emit("anti-flicker", idx)
)
self._anti_flicker_row = self._labeled("Anti-Flicker", self.anti_flicker)
self.add_widget(self._anti_flicker_row)
self.ev_slider = ParamSlider("EV Comp", min_val=0, max_val=16, default=8, step=1)
self.ev_slider.value_changed.connect(lambda v: self.param_changed.emit("exposure-ev", v))
self.add_widget(self.ev_slider)
self.iso_combo = QComboBox()
for iso in S3_ISO_VALUES:
self.iso_combo.addItem(str(iso), iso)
self.iso_combo.currentIndexChanged.connect(self._iso_changed)
self._iso_row = self._labeled("ISO", self.iso_combo)
self.add_widget(self._iso_row)
self.shutter_combo = QComboBox()
for label, us in SHUTTER_LABELS:
self.shutter_combo.addItem(label, us)
self.shutter_combo.setCurrentIndex(3)
self.shutter_combo.currentIndexChanged.connect(self._shutter_changed)
self._shutter_row = self._labeled("Shutter", self.shutter_combo)
self.add_widget(self._shutter_row)
self.exposure_lock_toggle = ToggleSwitch()
self.exposure_lock_toggle.toggled.connect(
lambda v: self.param_changed.emit("exposure-lock", v)
)
self._exp_lock_row = self._toggle_row("Exposure Lock", self.exposure_lock_toggle)
self.add_widget(self._exp_lock_row)
self._apply_mode_visibility(auto=True)
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def _mode_changed(self, index: int):
auto = (index == 0)
self.param_changed.emit("exposure-mode", index)
self._apply_mode_visibility(auto)
def _apply_mode_visibility(self, auto: bool):
self._anti_flicker_row.setVisible(auto)
self.ev_slider.setVisible(auto)
self._exp_lock_row.setVisible(auto)
self._iso_row.setVisible(not auto)
self._shutter_row.setVisible(not auto)
def _iso_changed(self, index: int):
if index >= 0:
iso_val = self.iso_combo.itemData(index)
self.param_changed.emit("exposure-iso", iso_val)
def _shutter_changed(self, index: int):
if index >= 0:
us_val = self.shutter_combo.itemData(index)
self.param_changed.emit("exposure-time", us_val)
def set_exposure_mode(self, value: int):
self.exposure_mode.set_selected(value, emit=False)
self._apply_mode_visibility(value == 0)
def set_hdr(self, enabled: bool):
self.hdr_toggle.set_checked(enabled, emit=False)
def set_anti_flicker(self, value: int):
self.anti_flicker.set_selected(value, emit=False)
def set_ev(self, raw: int):
self.ev_slider.set_value(float(raw), emit=False)
def set_iso(self, value: int):
"""Set ISO by raw protocol value."""
self.iso_combo.blockSignals(True)
for i in range(self.iso_combo.count()):
if self.iso_combo.itemData(i) == value:
self.iso_combo.setCurrentIndex(i)
break
self.iso_combo.blockSignals(False)
def set_shutter(self, us: int):
"""Set shutter by microsecond value."""
self.shutter_combo.blockSignals(True)
for i in range(self.shutter_combo.count()):
if self.shutter_combo.itemData(i) == us:
self.shutter_combo.setCurrentIndex(i)
break
self.shutter_combo.blockSignals(False)
def set_exposure_lock(self, enabled: bool):
self.exposure_lock_toggle.set_checked(enabled, emit=False)
@@ -0,0 +1,134 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Focus settings section."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QComboBox
from ..widgets import CollapsibleSection, SegmentButton, ToggleSwitch, ParamSlider
class FocusSection(CollapsibleSection):
"""Collapsible panel for focus settings with mode-dependent controls."""
param_changed = Signal(str, object)
MODES = ["AF-S", "Manual", "AF-C", "Face"]
MODE_VALUES = {"AF-S": 1, "Manual": 2, "AF-C": 3, "Face": 4}
def __init__(self, parent=None):
super().__init__("Focus", parent)
self.focus_mode = SegmentButton(self.MODES)
self.focus_mode.set_selected(2, emit=False)
self.focus_mode.selection_changed_text.connect(self._mode_changed)
self.add_widget(self._labeled("Mode", self.focus_mode))
self.focus_area_combo = QComboBox()
self.focus_area_combo.addItems(["Large", "Middle", "Small"])
self.focus_area_combo.currentIndexChanged.connect(
lambda idx: self.param_changed.emit("focus-level", idx)
)
self._focus_area_row = self._labeled("Focus Area", self.focus_area_combo)
self.add_widget(self._focus_area_row)
self.manual_focus = ParamSlider("Manual Focus", min_val=0, max_val=100, default=50, step=1)
self.manual_focus.value_changed.connect(
lambda v: self.param_changed.emit("focus-manual", v)
)
self._manual_focus_row = self.manual_focus
self.add_widget(self._manual_focus_row)
self.focus_power_toggle = ToggleSwitch(checked=True)
self.focus_power_toggle.toggled.connect(
lambda v: self.param_changed.emit("focus-caf", v)
)
self._focus_power_row = self._toggle_row("Focus Power", self.focus_power_toggle)
self.add_widget(self._focus_power_row)
self.focus_speed = SegmentButton(["Basic", "Quick"])
self.focus_speed.selection_changed.connect(
lambda idx: self.param_changed.emit("focus-trigger", idx)
)
self._focus_speed_row = self._labeled("Speed", self.focus_speed)
self.add_widget(self._focus_speed_row)
self._apply_mode_visibility("AF-C")
@staticmethod
def _labeled(text: str, widget: QWidget, stretch: bool = False) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
if stretch:
layout.addStretch()
layout.addWidget(widget)
if not stretch:
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def _mode_changed(self, mode_text: str):
value = self.MODE_VALUES.get(mode_text, 3)
self.param_changed.emit("focus-mode", value)
self._apply_mode_visibility(mode_text)
def _apply_mode_visibility(self, mode_text: str):
self._focus_area_row.setVisible(mode_text in ("AF-S", "AF-C"))
self._manual_focus_row.setVisible(mode_text == "Manual")
self._focus_power_row.setVisible(mode_text in ("AF-C", "Face"))
self._focus_speed_row.setVisible(mode_text == "AF-C")
def set_focus_mode(self, value: int):
"""Set focus mode by raw protocol value (1=AFS, 2=Manual, 3=AFC, 4=Face)."""
value_to_index = {1: 0, 2: 1, 3: 2, 4: 3}
idx = value_to_index.get(value, 2)
self.focus_mode.set_selected(idx, emit=False)
self._apply_mode_visibility(self.MODES[idx])
def set_focus_area(self, value: int):
self.focus_area_combo.blockSignals(True)
self.focus_area_combo.setCurrentIndex(value)
self.focus_area_combo.blockSignals(False)
def set_focus_power(self, enabled: bool):
self.focus_power_toggle.set_checked(enabled, emit=False)
def set_focus_speed(self, value: int):
self.focus_speed.set_selected(value, emit=False)
def set_manual_focus(self, value: int):
self.manual_focus.set_value(float(value), emit=False)
@@ -0,0 +1,78 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Graphics settings section (frame rate, lens shading)."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QComboBox
from ..widgets import CollapsibleSection, ToggleSwitch
class GraphicsSection(CollapsibleSection):
"""Collapsible panel for graphics/output settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Graphics Settings", parent)
self.framerate_combo = QComboBox()
self.framerate_combo.addItems(["25", "30", "50", "60"])
self.framerate_combo.setCurrentText("30")
self.framerate_combo.currentTextChanged.connect(
lambda v: self.param_changed.emit("frame-rate", int(v))
)
self.add_widget(self._labeled("Frame Rate", self.framerate_combo))
self.shading_toggle = ToggleSwitch(checked=True)
self.shading_toggle.toggled.connect(
lambda v: self.param_changed.emit("shading", v)
)
self.add_widget(self._toggle_row("Lens Shading", self.shading_toggle))
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def set_frame_rate(self, value: int):
self.framerate_combo.blockSignals(True)
self.framerate_combo.setCurrentText(str(value))
self.framerate_combo.blockSignals(False)
def set_shading(self, enabled: bool):
self.shading_toggle.set_checked(enabled, emit=False)
@@ -0,0 +1,108 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Image parameters panel that contains all collapsible settings sections."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QComboBox, QSizePolicy,
)
from PySide6.QtGui import QFont
from ..theme import COLOR_ACCENT, COLOR_BG_PANEL, COLOR_BORDER, COLOR_TEXT_SECONDARY
from ..widgets import PresetBar
from .graphics_section import GraphicsSection
from .image_section import ImageSection
from .focus_section import FocusSection
from .zoom_section import ZoomSection
from .exposure_section import ExposureSection
from .white_balance_section import WhiteBalanceSection
from .audio_section import AudioSection
class ImageParamsPanel(QWidget):
"""Scrollable panel containing all camera parameter sections."""
param_changed = Signal(str, object)
save_scene_requested = Signal()
refresh_requested = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("imageParamsPanel")
self.setStyleSheet(f"#imageParamsPanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
top_bar = QWidget()
top_bar.setFixedHeight(44)
top_layout = QHBoxLayout(top_bar)
top_layout.setContentsMargins(12, 6, 12, 6)
top_layout.setSpacing(8)
self.camera_combo = QComboBox()
self.camera_combo.addItem("Y-CAM (disconnected)")
self.camera_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
top_layout.addWidget(self.camera_combo)
self.capture_btn = QPushButton()
self.capture_btn.setText("\u25cf")
self.capture_btn.setFixedSize(32, 32)
self.capture_btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_ACCENT}; color: white; border: none;
border-radius: 16px; font-size: 18px; }}
QPushButton:hover {{ background-color: #f02574; }}
""")
top_layout.addWidget(self.capture_btn)
outer.addWidget(top_bar)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Image Parameters")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
self.refresh_btn = QPushButton("\u21bb")
self.refresh_btn.setFixedSize(28, 28)
self.refresh_btn.setToolTip("Refresh parameters from camera")
self.refresh_btn.setStyleSheet(f"""
QPushButton {{ background: transparent; color: {COLOR_TEXT_SECONDARY}; border: none; font-size: 16px; }}
QPushButton:hover {{ color: white; }}
""")
self.refresh_btn.clicked.connect(self.refresh_requested.emit)
header_layout.addWidget(self.refresh_btn)
self.save_scene_btn = QPushButton("Save Scene")
self.save_scene_btn.setProperty("accent", True)
self.save_scene_btn.setFixedHeight(28)
self.save_scene_btn.clicked.connect(self.save_scene_requested.emit)
header_layout.addWidget(self.save_scene_btn)
outer.addWidget(header)
self.preset_bar = PresetBar()
outer.addWidget(self.preset_bar)
self.graphics = GraphicsSection()
self.image = ImageSection()
self.focus = FocusSection()
self.zoom = ZoomSection()
self.exposure = ExposureSection()
self.white_balance = WhiteBalanceSection()
self.audio = AudioSection()
for section in [self.graphics, self.image, self.focus, self.zoom,
self.exposure, self.white_balance, self.audio]:
section.param_changed.connect(self.param_changed.emit)
outer.addWidget(section)
outer.addStretch()
@@ -0,0 +1,57 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Image settings section (sharpness, contrast, saturation, dynamic range)."""
from PySide6.QtCore import Signal
from ..widgets import CollapsibleSection, ParamSlider
class ImageSection(CollapsibleSection):
"""Collapsible panel for image quality settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Image Settings", parent)
self.sharpness = ParamSlider("Sharpness", min_val=-10, max_val=30, default=5, step=1)
self.sharpness.value_changed.connect(lambda v: self.param_changed.emit("sharpness", v))
self.add_widget(self.sharpness)
self.contrast = ParamSlider("Contrast", min_val=0, max_val=100, default=50, step=1)
self.contrast.value_changed.connect(lambda v: self.param_changed.emit("contrast", v))
self.add_widget(self.contrast)
self.saturation = ParamSlider("Saturation", min_val=0, max_val=100, default=50, step=1)
self.saturation.value_changed.connect(lambda v: self.param_changed.emit("saturation", v))
self.add_widget(self.saturation)
self.dynamic_range = ParamSlider("Dynamic Range", min_val=0, max_val=100, default=50, step=1)
self.dynamic_range.value_changed.connect(lambda v: self.param_changed.emit("dynamic-range", v))
self.add_widget(self.dynamic_range)
def set_sharpness(self, value: int):
self.sharpness.set_value(float(value), emit=False)
def set_contrast(self, value: int):
self.contrast.set_value(float(value), emit=False)
def set_saturation(self, value: int):
self.saturation.set_value(float(value), emit=False)
def set_dynamic_range(self, value: int):
self.dynamic_range.set_value(float(value), emit=False)
@@ -0,0 +1,159 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Settings panel with device info and SD card management."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QMessageBox
from PySide6.QtGui import QFont
from ..theme import COLOR_BG_PANEL, COLOR_TEXT_SECONDARY
from ..widgets import CollapsibleSection
class _DeviceInfoSection(CollapsibleSection):
"""Read-only device information display."""
def __init__(self, parent=None):
super().__init__("Device Info", parent)
self.firmware_label = QLabel("--")
self.add_widget(self._info_row("Firmware", self.firmware_label))
self.serial_label = QLabel("--")
self.add_widget(self._info_row("Serial Number", self.serial_label))
self.lens_label = QLabel("--")
self.add_widget(self._info_row("Lens Info", self.lens_label))
def set_firmware_info(self, text: str):
self.firmware_label.setText(text)
def set_serial(self, text: str):
self.serial_label.setText(text)
def set_lens_info(self, text: str):
self.lens_label.setText(text)
@staticmethod
def _info_row(label_text: str, value_label: QLabel) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(label_text)
lbl.setFixedWidth(110)
lbl.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
layout.addWidget(lbl)
layout.addWidget(value_label)
layout.addStretch()
return row
class _SDCardSection(CollapsibleSection):
"""SD card storage info and format action."""
format_sd_requested = Signal()
def __init__(self, parent=None):
super().__init__("SD Card", parent)
self.storage_label = QLabel("-- / -- MB")
self.add_widget(self._info_row("Storage", self.storage_label))
self.format_btn = QPushButton("Format SD Card")
self.format_btn.setProperty("accent", True)
self.format_btn.setFixedHeight(32)
self.format_btn.clicked.connect(self._confirm_format)
self.add_widget(self.format_btn)
def _confirm_format(self):
result = QMessageBox.warning(
self, "Format SD Card",
"All data on the SD card will be erased. Continue?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No,
)
if result == QMessageBox.StandardButton.Yes:
self.format_sd_requested.emit()
def set_disk_info(self, available: int, total: int):
self.storage_label.setText(f"{available} / {total} MB")
@staticmethod
def _info_row(label_text: str, value_label: QLabel) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(label_text)
lbl.setFixedWidth(110)
lbl.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
layout.addWidget(lbl)
layout.addWidget(value_label)
layout.addStretch()
return row
class SettingsPanel(QWidget):
"""Panel with device information and SD card management."""
param_changed = Signal(str, object)
format_sd_requested = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("settingsPanel")
self.setStyleSheet(f"#settingsPanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Settings")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
outer.addWidget(header)
self.device_info = _DeviceInfoSection()
outer.addWidget(self.device_info)
self.sd_card = _SDCardSection()
self.sd_card.format_sd_requested.connect(self.format_sd_requested.emit)
outer.addWidget(self.sd_card)
outer.addStretch()
def set_firmware_info(self, text: str):
self.device_info.set_firmware_info(text)
def set_serial(self, text: str):
self.device_info.set_serial(text)
def set_lens_info(self, text: str):
self.device_info.set_lens_info(text)
def set_disk_info(self, available: int, total: int):
self.sd_card.set_disk_info(available, total)
@@ -0,0 +1,165 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Stream output panel with HDMI and UVC settings."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QComboBox
from PySide6.QtGui import QFont
from ..theme import COLOR_BG_PANEL
from ..widgets import CollapsibleSection, ToggleSwitch
class _HDMISection(CollapsibleSection):
"""HDMI output format and color space settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("HDMI Output", parent)
self.format_combo = QComboBox()
for label, data in [("Auto", 0), ("4K", 1), ("1080p", 2), ("720p", 3)]:
self.format_combo.addItem(label, data)
self.format_combo.currentIndexChanged.connect(self._format_changed)
self.add_widget(self._labeled("Format", self.format_combo))
self.color_combo = QComboBox()
for label, data in [("Auto", 0), ("RGB", 1), ("YUV422", 2)]:
self.color_combo.addItem(label, data)
self.color_combo.currentIndexChanged.connect(self._color_changed)
self.add_widget(self._labeled("Color Space", self.color_combo))
def _format_changed(self, index: int):
if index >= 0:
self.param_changed.emit("hdmi-format", self.format_combo.itemData(index))
def _color_changed(self, index: int):
if index >= 0:
self.param_changed.emit("hdmi-color", self.color_combo.itemData(index))
def set_hdmi_format(self, value: int):
self.format_combo.blockSignals(True)
for i in range(self.format_combo.count()):
if self.format_combo.itemData(i) == value:
self.format_combo.setCurrentIndex(i)
break
self.format_combo.blockSignals(False)
def set_hdmi_color(self, value: int):
self.color_combo.blockSignals(True)
for i in range(self.color_combo.count()):
if self.color_combo.itemData(i) == value:
self.color_combo.setCurrentIndex(i)
break
self.color_combo.blockSignals(False)
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
class _UVCSection(CollapsibleSection):
"""UVC output enable/disable toggle."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("UVC Output", parent)
self.uvc_toggle = ToggleSwitch()
self.uvc_toggle.toggled.connect(lambda v: self.param_changed.emit("uvc", v))
self.add_widget(self._toggle_row("Enable", self.uvc_toggle))
def set_uvc_enabled(self, enabled: bool):
self.uvc_toggle.set_checked(enabled, emit=False)
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
class StreamPanel(QWidget):
"""Panel with HDMI and UVC output settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("streamPanel")
self.setStyleSheet(f"#streamPanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Stream")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
outer.addWidget(header)
self.hdmi = _HDMISection()
self.uvc = _UVCSection()
for section in [self.hdmi, self.uvc]:
section.param_changed.connect(self.param_changed.emit)
outer.addWidget(section)
outer.addStretch()
def set_hdmi_format(self, value: int):
self.hdmi.set_hdmi_format(value)
def set_hdmi_color(self, value: int):
self.hdmi.set_hdmi_color(value)
def set_uvc_enabled(self, enabled: bool):
self.uvc.set_uvc_enabled(enabled)
@@ -0,0 +1,158 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""White balance settings section with mode-dependent controls."""
from PySide6.QtCore import Signal
from PySide6.QtGui import QFont
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QToolButton
from ..widgets import CollapsibleSection, SegmentButton, ParamSlider, ToggleSwitch
class WhiteBalanceSection(CollapsibleSection):
"""Collapsible panel for white balance with auto/manual mode switching."""
param_changed = Signal(str, object)
eyedropper_requested = Signal()
def __init__(self, parent=None):
super().__init__("White Balance", parent)
self.wb_mode = SegmentButton(["Auto", "Manual"])
self.wb_mode.selection_changed_text.connect(self._mode_changed)
self._eyedropper_btn = QToolButton()
self._eyedropper_btn.setText("\u2316")
self._eyedropper_btn.setToolTip("Pick White Balance from Video")
self._eyedropper_btn.setCheckable(True)
btn_font = QFont()
btn_font.setPointSize(14)
self._eyedropper_btn.setFont(btn_font)
self._eyedropper_btn.setFixedSize(28, 28)
self._eyedropper_btn.toggled.connect(self._on_eyedropper_toggled)
mode_row = self._labeled("Mode", self.wb_mode)
mode_row.layout().addWidget(self._eyedropper_btn)
self.add_widget(mode_row)
self.wb_lock_toggle = ToggleSwitch()
self.wb_lock_toggle.toggled.connect(lambda v: self.param_changed.emit("wb-lock", v))
self._lock_row = self._toggle_row("WB Lock", self.wb_lock_toggle)
self.add_widget(self._lock_row)
self.temperature_slider = ParamSlider(
"Temperature", min_val=2000, max_val=10000, default=5000, step=50, suffix="K"
)
self.temperature_slider.value_changed.connect(
lambda v: self.param_changed.emit("wb-temp", v)
)
self.add_widget(self.temperature_slider)
self.temp_shift_slider = ParamSlider(
"Temp Shift", min_val=0, max_val=128, default=64, step=1
)
self.temp_shift_slider.value_changed.connect(
lambda v: self.param_changed.emit("wb-temp-shift", v)
)
self.add_widget(self.temp_shift_slider)
self.blue_offset_slider = ParamSlider(
"Blue Offset", min_val=0, max_val=20, default=10, step=1
)
self.blue_offset_slider.value_changed.connect(
lambda v: self.param_changed.emit("wb-blue-offset", v)
)
self.add_widget(self.blue_offset_slider)
self.red_offset_slider = ParamSlider(
"Red Offset", min_val=0, max_val=20, default=10, step=1
)
self.red_offset_slider.value_changed.connect(
lambda v: self.param_changed.emit("wb-red-offset", v)
)
self.add_widget(self.red_offset_slider)
self._apply_mode_visibility(auto=True)
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def _mode_changed(self, mode: str):
auto = (mode == "Auto")
value = 1 if auto else 0
self.param_changed.emit("wb-mode", value)
self._apply_mode_visibility(auto)
def _apply_mode_visibility(self, auto: bool):
self._lock_row.setVisible(auto)
self.temperature_slider.setVisible(not auto)
self.temp_shift_slider.setVisible(not auto)
self.blue_offset_slider.setVisible(not auto)
self.red_offset_slider.setVisible(not auto)
def _on_eyedropper_toggled(self, checked: bool):
if checked:
self.eyedropper_requested.emit()
def set_eyedropper_active(self, active: bool):
"""Set the eyedropper button check state without emitting signals."""
self._eyedropper_btn.blockSignals(True)
self._eyedropper_btn.setChecked(active)
self._eyedropper_btn.blockSignals(False)
def set_wb_mode(self, value: int):
"""Set WB mode by raw value (0=Manual, 1=Auto)."""
idx = 0 if value == 1 else 1
self.wb_mode.set_selected(idx, emit=False)
self._apply_mode_visibility(value == 1)
def set_wb_lock(self, enabled: bool):
self.wb_lock_toggle.set_checked(enabled, emit=False)
def set_temperature(self, value: int):
self.temperature_slider.set_value(float(value), emit=False)
def set_temp_shift(self, value: int):
self.temp_shift_slider.set_value(float(value), emit=False)
def set_blue_offset(self, value: int):
self.blue_offset_slider.set_value(float(value), emit=False)
def set_red_offset(self, value: int):
self.red_offset_slider.set_value(float(value), emit=False)
@@ -0,0 +1,38 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Zoom settings section."""
from PySide6.QtCore import Signal
from ..widgets import CollapsibleSection, ParamSlider
class ZoomSection(CollapsibleSection):
"""Collapsible panel for zoom control."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Zoom", parent)
self.zoom_slider = ParamSlider(
"Zoom", min_val=1.0, max_val=4.0, default=1.0, step=0.1, decimals=1, suffix="x"
)
self.zoom_slider.value_changed.connect(lambda v: self.param_changed.emit("zoom", v))
self.add_widget(self.zoom_slider)
def set_zoom(self, mult: float):
self.zoom_slider.set_value(mult, emit=False)
+76
View File
@@ -0,0 +1,76 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Left icon sidebar for navigation."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout, QToolButton, QSizePolicy
from PySide6.QtGui import QFont
from .theme import COLOR_BG_SIDEBAR, COLOR_BORDER
class Sidebar(QWidget):
"""48px-wide vertical icon sidebar."""
page_changed = Signal(int)
ICONS = [
("\u2699", "Parameters"),
("\U0001F3A8", "Color"),
("\u2328", "Console"),
("\U0001F4E1", "Stream"),
("\u2638", "Settings"),
]
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedWidth(48)
self.setObjectName("sidebar")
self.setStyleSheet(f"""
#sidebar {{ background-color: {COLOR_BG_SIDEBAR}; border-right: 1px solid {COLOR_BORDER}; }}
""")
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 8, 0, 8)
layout.setSpacing(4)
layout.setAlignment(Qt.AlignmentFlag.AlignTop)
self._buttons: list[QToolButton] = []
icon_font = QFont()
icon_font.setPointSize(16)
for i, (icon, tooltip) in enumerate(self.ICONS):
btn = QToolButton()
btn.setText(icon)
btn.setFont(icon_font)
btn.setToolTip(tooltip)
btn.setCheckable(True)
btn.setFixedSize(40, 40)
btn.clicked.connect(lambda checked, idx=i: self._on_click(idx))
self._buttons.append(btn)
layout.addWidget(btn, alignment=Qt.AlignmentFlag.AlignCenter)
layout.addStretch()
if self._buttons:
self._buttons[0].setChecked(True)
def set_active(self, index: int):
"""Set the active button without emitting page_changed."""
for i, btn in enumerate(self._buttons):
btn.setChecked(i == index)
def _on_click(self, index: int):
self.set_active(index)
self.page_changed.emit(index)
+236
View File
@@ -0,0 +1,236 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Dark theme stylesheet for YoloCam."""
# Palette constants used throughout the application
COLOR_BG_DARK = "#181818"
COLOR_BG_PANEL = "#242424"
COLOR_BG_SECTION_HEADER = "#2d2d2d"
COLOR_BG_INPUT = "#333333"
COLOR_BG_SIDEBAR = "#1e1e1e"
COLOR_ACCENT = "#e91e63"
COLOR_ACCENT_LIGHT = "#ff5252"
COLOR_SLIDER_EMPTY = "#444444"
COLOR_TOGGLE_OFF = "#555555"
COLOR_TEXT_PRIMARY = "#ffffff"
COLOR_TEXT_SECONDARY = "#aaaaaa"
COLOR_BORDER = "#3a3a3a"
def build_stylesheet() -> str:
return f"""
/* Global defaults */
QWidget {{
background-color: {COLOR_BG_DARK};
color: {COLOR_TEXT_PRIMARY};
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
font-size: 13px;
}}
/* Main window */
QMainWindow {{
background-color: {COLOR_BG_DARK};
}}
/* Scroll area used for the parameter panel */
QScrollArea {{
border: none;
background-color: {COLOR_BG_PANEL};
}}
QScrollArea > QWidget > QWidget {{
background-color: {COLOR_BG_PANEL};
}}
QScrollBar:vertical {{
background: {COLOR_BG_PANEL};
width: 8px;
margin: 0;
}}
QScrollBar::handle:vertical {{
background: {COLOR_SLIDER_EMPTY};
min-height: 30px;
border-radius: 4px;
}}
QScrollBar::handle:vertical:hover {{
background: {COLOR_TEXT_SECONDARY};
}}
QScrollBar::add-line:vertical,
QScrollBar::sub-line:vertical {{
height: 0;
}}
QScrollBar:horizontal {{
height: 0;
}}
/* Labels */
QLabel {{
background: transparent;
color: {COLOR_TEXT_PRIMARY};
padding: 0;
}}
/* ComboBox / dropdown */
QComboBox {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
border-radius: 4px;
padding: 4px 8px;
min-height: 24px;
}}
QComboBox:hover {{
border-color: {COLOR_ACCENT};
}}
QComboBox::drop-down {{
border: none;
width: 20px;
}}
QComboBox::down-arrow {{
image: none;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 5px solid {COLOR_TEXT_SECONDARY};
margin-right: 6px;
}}
QComboBox QAbstractItemView {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
selection-background-color: {COLOR_ACCENT};
selection-color: {COLOR_TEXT_PRIMARY};
}}
/* SpinBox */
QSpinBox, QDoubleSpinBox {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
border-radius: 4px;
padding: 2px 4px;
min-height: 22px;
}}
QSpinBox::up-button, QDoubleSpinBox::up-button {{
subcontrol-origin: border;
subcontrol-position: top right;
width: 16px;
border-left: 1px solid {COLOR_BORDER};
background: {COLOR_BG_SECTION_HEADER};
}}
QSpinBox::down-button, QDoubleSpinBox::down-button {{
subcontrol-origin: border;
subcontrol-position: bottom right;
width: 16px;
border-left: 1px solid {COLOR_BORDER};
background: {COLOR_BG_SECTION_HEADER};
}}
QSpinBox::up-arrow, QDoubleSpinBox::up-arrow {{
border-left: 3px solid transparent;
border-right: 3px solid transparent;
border-bottom: 4px solid {COLOR_TEXT_SECONDARY};
width: 0; height: 0;
}}
QSpinBox::down-arrow, QDoubleSpinBox::down-arrow {{
border-left: 3px solid transparent;
border-right: 3px solid transparent;
border-top: 4px solid {COLOR_TEXT_SECONDARY};
width: 0; height: 0;
}}
/* Push buttons */
QPushButton {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
border-radius: 4px;
padding: 5px 12px;
min-height: 24px;
}}
QPushButton:hover {{
background-color: {COLOR_SLIDER_EMPTY};
}}
QPushButton:pressed {{
background-color: {COLOR_BG_SECTION_HEADER};
}}
QPushButton[accent="true"] {{
background-color: {COLOR_ACCENT};
border: none;
font-weight: bold;
}}
QPushButton[accent="true"]:hover {{
background-color: #f02574;
}}
/* Tool buttons (sidebar icons) */
QToolButton {{
background: transparent;
border: none;
padding: 8px;
border-radius: 4px;
color: {COLOR_TEXT_SECONDARY};
}}
QToolButton:hover {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
}}
QToolButton:checked {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_ACCENT};
}}
/* Slider (default Qt slider, overridden by ParamSlider painting) */
QSlider::groove:horizontal {{
background: {COLOR_SLIDER_EMPTY};
height: 4px;
border-radius: 2px;
}}
QSlider::handle:horizontal {{
background: {COLOR_TEXT_PRIMARY};
width: 14px;
height: 14px;
margin: -5px 0;
border-radius: 7px;
}}
QSlider::sub-page:horizontal {{
background: qlineargradient(
x1:0, y1:0, x2:1, y2:0,
stop:0 {COLOR_ACCENT}, stop:1 {COLOR_ACCENT_LIGHT}
);
border-radius: 2px;
}}
/* Menu bar */
QMenuBar {{
background-color: {COLOR_BG_SIDEBAR};
color: {COLOR_TEXT_PRIMARY};
border-bottom: 1px solid {COLOR_BORDER};
}}
QMenuBar::item:selected {{
background-color: {COLOR_BG_INPUT};
}}
QMenu {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
}}
QMenu::item:selected {{
background-color: {COLOR_ACCENT};
}}
/* Frame separators */
QFrame[frameShape="4"] {{
color: {COLOR_BORDER};
max-height: 1px;
}}
"""
+232
View File
@@ -0,0 +1,232 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Video preview widget using OpenCV capture."""
import logging
import os
import re
import numpy as np
from PySide6.QtCore import Qt, QTimer, Signal, Slot
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy
from PySide6.QtGui import QImage, QPixmap, QFont
from .theme import COLOR_BG_DARK, COLOR_TEXT_SECONDARY
log = logging.getLogger(__name__)
YOLOCAM_VID = "46f8"
YOLOCAM_PID = "0855"
try:
import cv2
_HAS_CV2 = True
except ImportError:
_HAS_CV2 = False
log.warning("opencv-python not installed, video preview will be disabled")
def find_yolocam_device() -> int:
"""Scan /sys/class/video4linux for the YoloCam S3 UVC device.
Returns the lowest /dev/videoN index matching VID:PID 46f8:0855,
or -1 if not found.
"""
v4l_path = "/sys/class/video4linux"
if not os.path.isdir(v4l_path):
return -1
candidates = []
for entry in sorted(os.listdir(v4l_path)):
dev_path = os.path.join(v4l_path, entry, "device")
if not os.path.isdir(dev_path):
continue
try:
vid_path = os.path.join(dev_path, "..", "idVendor")
pid_path = os.path.join(dev_path, "..", "idProduct")
vid = open(os.path.realpath(vid_path)).read().strip()
pid = open(os.path.realpath(pid_path)).read().strip()
except (OSError, IOError):
continue
if vid == YOLOCAM_VID and pid == YOLOCAM_PID:
m = re.search(r"(\d+)$", entry)
if m:
candidates.append(int(m.group(1)))
if candidates:
return min(candidates)
return -1
class VideoWidget(QWidget):
"""Displays live camera feed from a UVC device, or a placeholder if disconnected."""
color_sampled = Signal(int, int, int)
eyedropper_deactivated = Signal()
def __init__(self, device_index: int = -1, parent=None):
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.setMinimumSize(320, 240)
self.setStyleSheet(f"background-color: {COLOR_BG_DARK};")
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._label = QLabel()
self._label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
layout.addWidget(self._label)
self._cap = None
self._timer = QTimer(self)
self._timer.timeout.connect(self._grab_frame)
self._last_frame = None
self._eyedropper_active = False
if device_index >= 0:
self.start(device_index)
else:
self._show_placeholder()
def auto_start(self):
"""Auto-detect the YoloCam UVC device and start capture."""
idx = find_yolocam_device()
if idx < 0:
log.info("YoloCam UVC device not found")
self._show_placeholder("YoloCam not detected")
return
log.info("YoloCam UVC device found at /dev/video%d", idx)
self.start(idx)
def start(self, device_index: int = 0):
"""Open the video device and begin grabbing frames."""
if not _HAS_CV2:
self._show_placeholder("OpenCV not available")
return
self.stop()
self._cap = cv2.VideoCapture(device_index)
self._cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
if not self._cap.isOpened():
log.warning("Could not open video device %d", device_index)
self._cap = None
self._show_placeholder()
return
self._timer.start(33)
def stop(self):
"""Stop capturing and release the device."""
self._timer.stop()
if self._cap is not None:
self._cap.release()
self._cap = None
@Slot()
def _grab_frame(self):
if self._cap is None:
return
ret, frame = self._cap.read()
if not ret:
return
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self._last_frame = rgb
h, w, ch = rgb.shape
bytes_per_line = ch * w
qimg = QImage(rgb.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
scaled = qimg.scaled(
self._label.size(),
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
self._label.setPixmap(QPixmap.fromImage(scaled))
def set_eyedropper_mode(self, enabled: bool):
"""Activate or deactivate eyedropper sampling mode."""
self._eyedropper_active = enabled
if enabled:
self.setCursor(Qt.CursorShape.CrossCursor)
else:
self.unsetCursor()
def mousePressEvent(self, event):
if not self._eyedropper_active:
super().mousePressEvent(event)
return
self._eyedropper_active = False
self.unsetCursor()
if self._last_frame is None:
self.eyedropper_deactivated.emit()
return
# Map click position to frame coordinates
click_pos = self._label.mapFromParent(event.position().toPoint())
frame_h, frame_w = self._last_frame.shape[:2]
label_w = self._label.width()
label_h = self._label.height()
scale = min(label_w / frame_w, label_h / frame_h)
scaled_w = frame_w * scale
scaled_h = frame_h * scale
offset_x = (label_w - scaled_w) / 2
offset_y = (label_h - scaled_h) / 2
fx = (click_pos.x() - offset_x) * frame_w / scaled_w
fy = (click_pos.y() - offset_y) * frame_h / scaled_h
if fx < 0 or fx >= frame_w or fy < 0 or fy >= frame_h:
self.eyedropper_deactivated.emit()
return
# Average an 11x11 neighborhood
cx, cy = int(fx), int(fy)
half = 5
x0, x1 = max(0, cx - half), min(frame_w, cx + half + 1)
y0, y1 = max(0, cy - half), min(frame_h, cy + half + 1)
patch = self._last_frame[y0:y1, x0:x1]
avg = patch.mean(axis=(0, 1))
r, g, b = int(avg[0]), int(avg[1]), int(avg[2])
self.color_sampled.emit(r, g, b)
self.eyedropper_deactivated.emit()
def _show_placeholder(self, text: str = "No camera connected"):
self._label.setPixmap(QPixmap())
self._label.setText(text)
placeholder_font = QFont()
placeholder_font.setPointSize(14)
self._label.setFont(placeholder_font)
self._label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY}; background: transparent;")
def closeEvent(self, event):
self.stop()
super().closeEvent(event)
@@ -0,0 +1,30 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .collapsible_section import CollapsibleSection
from .param_slider import ParamSlider
from .toggle_switch import ToggleSwitch
from .segment_button import SegmentButton
from .preset_bar import PresetBar
from .color_wheel import ColorWheel
__all__ = [
"CollapsibleSection",
"ParamSlider",
"ToggleSwitch",
"SegmentButton",
"PresetBar",
"ColorWheel",
]
@@ -0,0 +1,162 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Collapsible section widget with animated expand/collapse."""
from PySide6.QtCore import Qt, QPropertyAnimation, QEasingCurve, Property, QPointF
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QFrame, QSizePolicy,
)
from PySide6.QtGui import QPainter, QColor, QFont
from ..theme import COLOR_BG_SECTION_HEADER, COLOR_TEXT_PRIMARY, COLOR_BORDER
class _HeaderBar(QWidget):
"""Clickable header bar with triangle arrow and title."""
def __init__(self, title: str, parent=None):
super().__init__(parent)
self.title = title
self._expanded = True
self.setFixedHeight(32)
self.setCursor(Qt.CursorShape.PointingHandCursor)
@property
def expanded(self) -> bool:
return self._expanded
@expanded.setter
def expanded(self, value: bool):
self._expanded = value
self.update()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.fillRect(self.rect(), QColor(COLOR_BG_SECTION_HEADER))
arrow_x = 12
arrow_y = self.height() // 2
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(COLOR_TEXT_PRIMARY))
if self._expanded:
p.drawPolygon([
QPointF(arrow_x - 4, arrow_y - 2),
QPointF(arrow_x + 4, arrow_y - 2),
QPointF(arrow_x, arrow_y + 3),
])
else:
p.drawPolygon([
QPointF(arrow_x - 2, arrow_y - 4),
QPointF(arrow_x + 3, arrow_y),
QPointF(arrow_x - 2, arrow_y + 4),
])
p.setPen(QColor(COLOR_TEXT_PRIMARY))
font = QFont()
font.setBold(True)
font.setPointSize(10)
p.setFont(font)
p.drawText(
28, 0, self.width() - 32, self.height(),
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
self.title,
)
p.end()
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.parent().toggle()
class CollapsibleSection(QWidget):
"""A section with a clickable header that expands and collapses its content area."""
def __init__(self, title: str, parent=None, expanded: bool = False):
super().__init__(parent)
self._expanded = expanded
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self._header = _HeaderBar(title, self)
layout.addWidget(self._header)
self._content = QWidget()
self._content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
self._content_layout = QVBoxLayout(self._content)
self._content_layout.setContentsMargins(8, 6, 8, 6)
self._content_layout.setSpacing(6)
layout.addWidget(self._content)
self._animation = QPropertyAnimation(self, b"content_height")
self._animation.setDuration(200)
self._animation.setEasingCurve(QEasingCurve.Type.InOutQuad)
if not expanded:
self._content.setMaximumHeight(0)
self._header.expanded = False
@property
def content_layout(self) -> QVBoxLayout:
return self._content_layout
def add_widget(self, widget: QWidget):
self._content_layout.addWidget(widget)
def add_layout(self, layout):
self._content_layout.addLayout(layout)
def _get_content_height(self) -> int:
return self._content.maximumHeight()
def _set_content_height(self, h: int):
self._content.setMaximumHeight(h)
content_height = Property(int, _get_content_height, _set_content_height)
def toggle(self):
self._expanded = not self._expanded
self._header.expanded = self._expanded
target_height = self._content.sizeHint().height() if self._expanded else 0
self._animation.stop()
self._animation.setStartValue(self._content.maximumHeight())
self._animation.setEndValue(target_height)
if self._expanded:
self._animation.finished.connect(self._unlock_height)
self._animation.start()
def _unlock_height(self):
"""Remove height cap after expansion so content can resize freely."""
if self._expanded:
self._content.setMaximumHeight(16777215)
try:
self._animation.finished.disconnect(self._unlock_height)
except TypeError:
pass
def is_expanded(self) -> bool:
return self._expanded
@@ -0,0 +1,798 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""HSV color wheel widget with Fast and Professional modes.
Fast mode provides a two-point color remapping interface: the user clicks to
select a source color region, then drags to a destination. The shift is
propagated across the internal polar grid with linear falloff and sent as a
CLUT to the camera.
Professional mode overlays a polar grid of draggable control points for
per-region color grading adjustments.
"""
import copy
import math
from PySide6.QtCore import Qt, Signal, QPointF, QRectF
from PySide6.QtWidgets import QWidget
from PySide6.QtGui import (
QPainter, QColor, QImage, QPen, QBrush,
QConicalGradient, QRadialGradient, QPixmap,
)
from ..theme import COLOR_BG_PANEL, COLOR_ACCENT
from yolocam.clut import (
HUE_SECTORS, SAT_COLUMNS, FULL_R_VALUE, INTERVAL_THETA, INTERVAL_R_NORM,
init_fast_grid, init_luma_grid, calc_rows_data,
)
_TWO_PI = 2.0 * math.pi
_SAT_RINGS = SAT_COLUMNS
_HUE_STEP_DEG = INTERVAL_THETA
_GRID_POINT_RADIUS = 3.5
_GRID_HIT_RADIUS = 8.0
_GRID_LINE_COLOR = QColor(255, 255, 255, 64)
_ACCENT_COLOR = QColor(COLOR_ACCENT)
_HOME_LINE_COLOR = QColor(255, 255, 255, 40)
_SOURCE_COLOR = QColor(255, 0, 67, 200)
_DEST_COLOR = QColor(255, 255, 255, 200)
_ARROW_COLOR = QColor(255, 255, 255, 160)
def _polar_to_xy(center_x, center_y, radius, angle_rad):
"""Convert polar coordinates to pixel position (math convention, y-up)."""
return (
center_x + radius * math.cos(angle_rad),
center_y - radius * math.sin(angle_rad),
)
def _xy_to_polar(cx, cy, px, py):
"""Convert pixel position to (angle_rad, distance) from center."""
dx = px - cx
dy = py - cy
dist = math.sqrt(dx * dx + dy * dy)
angle = math.atan2(-dy, dx)
if angle < 0:
angle += _TWO_PI
return angle, dist
class ColorWheel(QWidget):
"""Circular HSV color wheel with click/drag selection.
Supports two modes:
- "fast" (default): two-point color remapping via CLUT
- "professional": polar grid of draggable control points for
per-region color grading
Hue maps to angle around the circumference, saturation maps to
distance from center. Brightness (value) is controlled externally.
"""
hue_changed = Signal(int)
saturation_changed = Signal(int)
brightness_changed = Signal(int)
color_changed = Signal(int, int, int)
grid_changed = Signal(object)
WHEEL_SIZE = 280
INDICATOR_RADIUS = 6
def __init__(self, parent=None):
super().__init__(parent)
self._hue = 0
self._saturation = 0
self._brightness = 100
self._dragging = False
self._mode = "fast"
self._wheel_pixmap = None
self._wheel_center = QPointF(self.WHEEL_SIZE / 2.0, self.WHEEL_SIZE / 2.0)
self._wheel_radius = self.WHEEL_SIZE / 2.0 - 2.0
# Professional mode state: displacement (dx, dy) per grid point
self._grid_disp = [[(0.0, 0.0) for _ in range(_SAT_RINGS)] for _ in range(HUE_SECTORS)]
self._grid_drag_idx = None
self._grid_hover_idx = None
# Fast mode state
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
self._fast_drags = [] # persistent drag ops: [{"line","col","dest_theta","dest_r"}, ...]
self._fast_active_idx = None # index of drag being edited, or None
self._fast_new_source = None # (line, col) for new drag being created
self._fast_dest_px = None # pixel coords during drag
self._fast_hover_idx = None # index of hovered drag source, or None
self.setFixedSize(self.WHEEL_SIZE, self.WHEEL_SIZE)
self.setMouseTracking(True)
self._rebuild_wheel()
# -- Public API --
def hue(self) -> int:
return self._hue
def saturation(self) -> int:
return self._saturation
def brightness(self) -> int:
return self._brightness
def set_hue(self, value: int):
value = max(0, min(360, value))
if self._hue == value:
return
self._hue = value
self.update()
def set_saturation(self, value: int):
value = max(0, min(100, value))
if self._saturation == value:
return
self._saturation = value
self.update()
def set_brightness(self, value: int):
value = max(0, min(100, value))
if self._brightness == value:
return
self._brightness = value
self.brightness_changed.emit(self._brightness)
self.color_changed.emit(self._hue, self._saturation, self._brightness)
self.update()
def mode(self) -> str:
return self._mode
def set_mode(self, mode: str):
if mode not in ("fast", "professional"):
return
if self._mode == mode:
return
old_mode = self._mode
self._mode = mode
self._grid_drag_idx = None
self._grid_hover_idx = None
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
self._dragging = False
if old_mode == "fast" and mode == "professional":
self._sync_fast_to_professional()
self.grid_changed.emit(self.grid_data())
self.update()
def grid_data(self) -> dict:
"""Return the current grid displacement state as HSV adjustment dicts.
Format: {"hue": 25x12, "sat": 25x12, "luma": 25x12}
Row 24 wraps to row 0 for interpolation continuity.
"""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
hue_grid = []
sat_grid = []
luma_grid = []
for h in range(HUE_SECTORS + 1):
h_idx = h % HUE_SECTORS
hue_row = []
sat_row = []
luma_row = []
for s in range(_SAT_RINGS):
dx, dy = self._grid_disp[h_idx][s]
hx, hy = self._grid_home_pos(h_idx, s)
if abs(dx) < 0.01 and abs(dy) < 0.01:
hue_row.append(0.0)
sat_row.append(0.0)
else:
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
cur_angle, cur_dist = _xy_to_polar(cx, cy, hx + dx, hy + dy)
angle_delta = math.degrees(cur_angle - home_angle)
if angle_delta > 180:
angle_delta -= 360
if angle_delta < -180:
angle_delta += 360
sat_delta = ((cur_dist - home_dist) / self._wheel_radius) * 100.0
hue_row.append(round(angle_delta, 2))
sat_row.append(round(sat_delta, 2))
luma_row.append(0.0)
hue_grid.append(hue_row)
sat_grid.append(sat_row)
luma_grid.append(luma_row)
return {"hue": hue_grid, "sat": sat_grid, "luma": luma_grid}
def fast_grid_data(self) -> dict:
"""Return the Fast mode grid state for CLUT computation."""
return {
"mode": "fast",
"grid": copy.deepcopy(self._fast_grid),
"luma": copy.deepcopy(self._fast_luma),
}
def set_grid_data(self, data: dict):
"""Load grid state from a dict (inverse of grid_data)."""
hue_grid = data.get("hue", [])
sat_grid = data.get("sat", [])
cx = self._wheel_center.x()
cy = self._wheel_center.y()
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hue_delta = 0.0
sat_delta = 0.0
if h < len(hue_grid) and s < len(hue_grid[h]):
hue_delta = hue_grid[h][s]
if h < len(sat_grid) and s < len(sat_grid[h]):
sat_delta = sat_grid[h][s]
if abs(hue_delta) < 0.01 and abs(sat_delta) < 0.01:
self._grid_disp[h][s] = (0.0, 0.0)
continue
hx, hy = self._grid_home_pos(h, s)
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
new_angle = home_angle + math.radians(hue_delta)
new_dist = home_dist + (sat_delta / 100.0) * self._wheel_radius
new_dist = max(0, min(self._wheel_radius, new_dist))
nx, ny = _polar_to_xy(cx, cy, new_dist, new_angle)
self._grid_disp[h][s] = (nx - hx, ny - hy)
self.update()
def reset_grid(self):
"""Reset all grid points to home positions (both modes)."""
self._grid_disp = [[(0.0, 0.0) for _ in range(_SAT_RINGS)] for _ in range(HUE_SECTORS)]
self._grid_drag_idx = None
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
self._fast_drags = []
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
if self._mode == "fast":
self.grid_changed.emit(self.fast_grid_data())
else:
self.grid_changed.emit(self.grid_data())
self.update()
# -- Painting --
def _rebuild_wheel(self):
"""Pre-render the HSV wheel as a QPixmap.
Always renders at full brightness so the color spectrum is visible regardless
of the camera's brightness parameter value.
"""
size = self.WHEEL_SIZE
pixmap = QPixmap(size, size)
pixmap.fill(Qt.GlobalColor.transparent)
p = QPainter(pixmap)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
cx = size / 2.0
cy = size / 2.0
radius = self._wheel_radius
hue_gradient = QConicalGradient(cx, cy, 0)
num_stops = 12
for i in range(num_stops + 1):
frac = i / num_stops
hue_val = frac * 360.0
if hue_val >= 360.0:
hue_val = 0.0
color = QColor.fromHsvF(hue_val / 360.0, 1.0, 1.0)
hue_gradient.setColorAt(frac, color)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QBrush(hue_gradient))
p.drawEllipse(QPointF(cx, cy), radius, radius)
sat_gradient = QRadialGradient(cx, cy, radius)
center_color = QColor(255, 255, 255, 255)
edge_color = QColor(255, 255, 255, 0)
sat_gradient.setColorAt(0.0, center_color)
sat_gradient.setColorAt(1.0, edge_color)
p.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceOver)
p.setBrush(QBrush(sat_gradient))
p.drawEllipse(QPointF(cx, cy), radius, radius)
p.end()
self._wheel_pixmap = pixmap
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(COLOR_BG_PANEL))
p.drawEllipse(self._wheel_center, self._wheel_radius + 2, self._wheel_radius + 2)
if self._wheel_pixmap:
p.drawPixmap(0, 0, self._wheel_pixmap)
if self._mode == "fast":
self._paint_fast_mode(p)
else:
self._paint_grid(p)
p.end()
def _paint_fast_mode(self, p: QPainter):
"""Draw Fast mode persistent drag arrows and active drag."""
half = 5.0
for i, drag in enumerate(self._fast_drags):
sx, sy = self._grid_pos_to_pixel(drag["line"], drag["col"])
dx, dy = self._polar_norm_to_pixel(drag["dest_theta"], drag["dest_r"])
active = (i == self._fast_active_idx)
hovered = (i == self._fast_hover_idx) and not self._dragging
alpha = 220 if (active or hovered) else 140
src_half = half + 2.0 if hovered else half
p.setPen(QPen(QColor(255, 0, 67, alpha), 2.5 if hovered else 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRect(QRectF(sx - src_half, sy - src_half, src_half * 2, src_half * 2))
p.setPen(QPen(QColor(255, 255, 255, alpha), 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawEllipse(QPointF(dx, dy), self.INDICATOR_RADIUS, self.INDICATOR_RADIUS)
self._paint_arrow(p, sx, sy, dx, dy, alpha)
if self._fast_dest_px is not None:
source = self._fast_new_source
if self._fast_active_idx is not None and self._fast_active_idx < len(self._fast_drags):
d = self._fast_drags[self._fast_active_idx]
source = (d["line"], d["col"])
if source is not None:
sx, sy = self._grid_pos_to_pixel(*source)
dx, dy = self._fast_dest_px
p.setPen(QPen(_SOURCE_COLOR, 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRect(QRectF(sx - half, sy - half, half * 2, half * 2))
p.setPen(QPen(_DEST_COLOR, 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawEllipse(QPointF(dx, dy), self.INDICATOR_RADIUS, self.INDICATOR_RADIUS)
self._paint_arrow(p, sx, sy, dx, dy)
def _paint_arrow(self, p: QPainter, x1, y1, x2, y2, alpha=160):
"""Draw an arrow from (x1,y1) to (x2,y2)."""
dx = x2 - x1
dy = y2 - y1
length = math.sqrt(dx * dx + dy * dy)
if length < 5:
return
p.setPen(QPen(QColor(255, 255, 255, alpha), 1.5))
# Shaft
p.drawLine(QPointF(x1, y1), QPointF(x2, y2))
# Arrowhead
angle = math.atan2(dy, dx)
head_len = 8.0
spread = math.pi / 6.0
p.drawLine(
QPointF(x2, y2),
QPointF(x2 - head_len * math.cos(angle - spread), y2 - head_len * math.sin(angle - spread)),
)
p.drawLine(
QPointF(x2, y2),
QPointF(x2 - head_len * math.cos(angle + spread), y2 - head_len * math.sin(angle + spread)),
)
def _paint_grid(self, p: QPainter):
"""Draw the polar grid mesh and control points over the wheel."""
grid_pen = QPen(_GRID_LINE_COLOR, 0.75)
p.setPen(grid_pen)
p.setBrush(Qt.BrushStyle.NoBrush)
for s in range(_SAT_RINGS):
points = []
for h in range(HUE_SECTORS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
points.append(QPointF(hx + dx, hy + dy))
for i in range(HUE_SECTORS):
next_i = (i + 1) % HUE_SECTORS
p.drawLine(points[i], points[next_i])
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS - 1):
hx1, hy1 = self._grid_home_pos(h, s)
dx1, dy1 = self._grid_disp[h][s]
hx2, hy2 = self._grid_home_pos(h, s + 1)
dx2, dy2 = self._grid_disp[h][s + 1]
p.drawLine(QPointF(hx1 + dx1, hy1 + dy1), QPointF(hx2 + dx2, hy2 + dy2))
home_pen = QPen(_HOME_LINE_COLOR, 0.5, Qt.PenStyle.DotLine)
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
dx, dy = self._grid_disp[h][s]
if abs(dx) < 0.5 and abs(dy) < 0.5:
continue
hx, hy = self._grid_home_pos(h, s)
p.setPen(home_pen)
p.drawLine(QPointF(hx, hy), QPointF(hx + dx, hy + dy))
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
px, py = hx + dx, hy + dy
displaced = abs(dx) > 0.5 or abs(dy) > 0.5
hovered = self._grid_hover_idx == (h, s)
r = _GRID_POINT_RADIUS + (1.0 if hovered else 0.0)
if displaced:
p.setPen(QPen(QColor(40, 40, 40), 1.0))
p.setBrush(QBrush(_ACCENT_COLOR))
elif hovered:
p.setPen(QPen(QColor(40, 40, 40), 1.0))
p.setBrush(QBrush(QColor(255, 255, 255)))
else:
p.setPen(QPen(QColor(60, 60, 60), 0.75))
p.setBrush(QBrush(QColor(255, 255, 255, 200)))
p.drawEllipse(QPointF(px, py), r, r)
def _grid_home_pos(self, h_idx: int, s_idx: int) -> tuple:
"""Compute the undisplaced pixel position for grid point (h_idx, s_idx).
s_idx 0 is nearest center, s_idx (_SAT_RINGS-1) is at wheel edge.
"""
angle_rad = (h_idx / HUE_SECTORS) * _TWO_PI
frac = (s_idx + 1) / _SAT_RINGS
dist = frac * self._wheel_radius
return _polar_to_xy(self._wheel_center.x(), self._wheel_center.y(), dist, angle_rad)
def _grid_pos_to_pixel(self, line_num: int, col_num: int) -> tuple:
"""Convert a Fast mode grid position to pixel coordinates.
Uses the mathematical grid positions (same coordinate system as the algo).
col_num 0 is center, col_num 11 is outermost.
"""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
theta_deg = line_num * INTERVAL_THETA
r_norm = col_num * INTERVAL_R_NORM
pixel_r = r_norm / FULL_R_VALUE * self._wheel_radius
angle_rad = math.radians(theta_deg)
return (cx + pixel_r * math.cos(angle_rad), cy - pixel_r * math.sin(angle_rad))
def _polar_norm_to_pixel(self, theta_deg: float, r_norm: float) -> tuple:
"""Convert absolute polar coordinates to pixel position."""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
pixel_r = r_norm / FULL_R_VALUE * self._wheel_radius
angle_rad = math.radians(theta_deg)
return (cx + pixel_r * math.cos(angle_rad), cy - pixel_r * math.sin(angle_rad))
def _pixel_to_polar_norm(self, px: float, py: float) -> tuple:
"""Convert pixel position to (theta_degrees, r_normalized)."""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = px - cx
dy = cy - py
r_pixels = math.sqrt(dx * dx + dy * dy)
theta_deg = math.degrees(math.atan2(dy, dx))
if theta_deg < 0:
theta_deg += 360.0
r_norm = r_pixels / self._wheel_radius * FULL_R_VALUE
return theta_deg, r_norm
def _find_nearest_fast_point(self, px: float, py: float) -> tuple:
"""Find the nearest Fast grid point to a pixel position.
Returns (line_num, col_num). Skips center column (col 0).
"""
theta_deg, r_norm = self._pixel_to_polar_norm(px, py)
line = round(theta_deg / INTERVAL_THETA) % HUE_SECTORS
col = round(r_norm / INTERVAL_R_NORM)
col = max(1, min(SAT_COLUMNS - 1, col))
return line, col
def _find_nearest_drag_source(self, px: float, py: float):
"""Find the index of the nearest committed drag source within hit radius, or None."""
best_idx = None
best_dist = _GRID_HIT_RADIUS * 1.5
for i, drag in enumerate(self._fast_drags):
sx, sy = self._grid_pos_to_pixel(drag["line"], drag["col"])
d = math.sqrt((px - sx) ** 2 + (py - sy) ** 2)
if d < best_dist:
best_dist = d
best_idx = i
return best_idx
def _rebuild_fast_grid(self):
"""Recompute fast grid from scratch by replaying all committed drags."""
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
for drag in self._fast_drags:
calc_rows_data(
drag["line"], drag["col"],
drag["dest_theta"], drag["dest_r"],
self._fast_grid,
)
def _sync_fast_to_professional(self):
"""Update professional grid displacements to reflect fast grid changes."""
identity = init_fast_grid()
cx = self._wheel_center.x()
cy = self._wheel_center.y()
for h in range(HUE_SECTORS):
for s in range(SAT_COLUMNS):
id_theta, id_r = identity[h][s]
cur_theta, cur_r = self._fast_grid[h][s]
theta_delta = cur_theta - id_theta
if theta_delta > 180:
theta_delta -= 360
if theta_delta < -180:
theta_delta += 360
r_delta = cur_r - id_r
if abs(theta_delta) < 0.01 and abs(r_delta) < 0.001:
self._grid_disp[h][s] = (0.0, 0.0)
continue
hx, hy = self._grid_home_pos(h, s)
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
new_angle = home_angle + math.radians(theta_delta)
r_delta_px = (r_delta / FULL_R_VALUE) * self._wheel_radius
new_dist = max(0, min(self._wheel_radius, home_dist + r_delta_px))
nx, ny = _polar_to_xy(cx, cy, new_dist, new_angle)
self._grid_disp[h][s] = (nx - hx, ny - hy)
def _indicator_pos(self) -> tuple:
"""Compute pixel position of the current hue/saturation indicator."""
angle_rad = (self._hue / 360.0) * _TWO_PI
dist = (self._saturation / 100.0) * self._wheel_radius
x = self._wheel_center.x() + dist * math.cos(angle_rad)
y = self._wheel_center.y() - dist * math.sin(angle_rad)
return x, y
# -- Mouse interaction --
def mousePressEvent(self, event):
if self._mode == "fast":
pos = event.position()
if event.button() == Qt.MouseButton.LeftButton:
idx = self._find_nearest_drag_source(pos.x(), pos.y())
if idx is not None:
self._fast_active_idx = idx
self._fast_new_source = None
else:
line, col = self._find_nearest_fast_point(pos.x(), pos.y())
self._fast_new_source = (line, col)
self._fast_active_idx = None
self._fast_dest_px = None
self._fast_hover_idx = None
self._dragging = True
self.setCursor(Qt.CursorShape.ClosedHandCursor)
self.update()
elif event.button() == Qt.MouseButton.RightButton:
idx = self._find_nearest_drag_source(pos.x(), pos.y())
if idx is not None:
del self._fast_drags[idx]
self._rebuild_fast_grid()
self.grid_changed.emit(self.fast_grid_data())
self.update()
return
pos = event.position()
if event.button() == Qt.MouseButton.RightButton:
hit = self._hit_test_grid(pos)
if hit is not None:
self._grid_disp[hit[0]][hit[1]] = (0.0, 0.0)
else:
self.reset_grid()
return
self.grid_changed.emit(self.grid_data())
self.update()
return
if event.button() == Qt.MouseButton.LeftButton:
hit = self._hit_test_grid(pos)
if hit is not None:
self._grid_drag_idx = hit
self._dragging = True
def mouseMoveEvent(self, event):
pos = event.position()
if self._mode == "fast":
if self._dragging and (self._fast_new_source is not None or self._fast_active_idx is not None):
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = pos.x() - cx
dy = pos.y() - cy
dist = math.sqrt(dx * dx + dy * dy)
if dist > self._wheel_radius:
scale = self._wheel_radius / dist
px = cx + dx * scale
py = cy + dy * scale
else:
px, py = pos.x(), pos.y()
self._fast_dest_px = (px, py)
self.update()
else:
hover = self._find_nearest_drag_source(pos.x(), pos.y())
if hover != self._fast_hover_idx:
self._fast_hover_idx = hover
self.setCursor(
Qt.CursorShape.OpenHandCursor if hover is not None
else Qt.CursorShape.CrossCursor
)
self.update()
return
if self._dragging and self._grid_drag_idx is not None:
self._drag_grid_point(pos)
return
hit = self._hit_test_grid(pos)
if hit != self._grid_hover_idx:
self._grid_hover_idx = hit
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
if self._mode == "fast" and self._fast_dest_px is not None:
dest_theta, dest_r = self._pixel_to_polar_norm(*self._fast_dest_px)
if self._fast_active_idx is not None and self._fast_active_idx < len(self._fast_drags):
d = self._fast_drags[self._fast_active_idx]
d["dest_theta"] = dest_theta
d["dest_r"] = dest_r
elif self._fast_new_source is not None:
line, col = self._fast_new_source
self._fast_drags.append({
"line": line, "col": col,
"dest_theta": dest_theta, "dest_r": dest_r,
})
self._rebuild_fast_grid()
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
self.grid_changed.emit(self.fast_grid_data())
self.update()
elif self._mode == "professional" and self._grid_drag_idx is not None:
self.grid_changed.emit(self.grid_data())
self._dragging = False
self._grid_drag_idx = None
self.setCursor(Qt.CursorShape.CrossCursor)
def _hit_test_grid(self, pos: QPointF):
"""Find the nearest grid point within hit radius, or None."""
px, py = pos.x(), pos.y()
best = None
best_dist = _GRID_HIT_RADIUS
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
gx, gy = hx + dx, hy + dy
d = math.sqrt((px - gx) ** 2 + (py - gy) ** 2)
if d < best_dist:
best_dist = d
best = (h, s)
return best
def _drag_grid_point(self, pos: QPointF):
"""Update the displacement of the currently dragged grid point."""
h, s = self._grid_drag_idx
hx, hy = self._grid_home_pos(h, s)
px, py = pos.x(), pos.y()
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = px - cx
dy = py - cy
dist = math.sqrt(dx * dx + dy * dy)
if dist > self._wheel_radius:
scale = self._wheel_radius / dist
px = cx + dx * scale
py = cy + dy * scale
self._grid_disp[h][s] = (px - hx, py - hy)
self.update()
@@ -0,0 +1,140 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Parameter slider widget with label, slider, and spinbox."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QHBoxLayout, QLabel, QSlider, QSpinBox, QDoubleSpinBox, QSizePolicy,
)
class ParamSlider(QWidget):
"""Row layout with label, slider, and spinbox for adjusting a parameter."""
value_changed = Signal(float)
def __init__(self, label: str, min_val: float = 0, max_val: float = 100,
default: float = 50, step: float = 1, decimals: int = 0,
suffix: str = "", parent=None):
super().__init__(parent)
self._min = min_val
self._max = max_val
self._step = step
self._decimals = decimals
self._block_signals = False
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
self._label = QLabel(label)
self._label.setFixedWidth(110)
self._label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
layout.addWidget(self._label)
self._slider = QSlider(Qt.Orientation.Horizontal)
self._slider.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
if decimals > 0:
self._scale = 10 ** decimals
self._slider.setMinimum(int(min_val * self._scale))
self._slider.setMaximum(int(max_val * self._scale))
self._slider.setSingleStep(int(step * self._scale))
self._slider.setValue(int(default * self._scale))
self._spin = QDoubleSpinBox()
self._spin.setDecimals(decimals)
self._spin.setMinimum(min_val)
self._spin.setMaximum(max_val)
self._spin.setSingleStep(step)
self._spin.setValue(default)
if suffix:
self._spin.setSuffix(suffix)
self._slider.valueChanged.connect(self._slider_moved_float)
self._spin.valueChanged.connect(self._spin_changed_float)
else:
self._scale = 1
self._slider.setMinimum(int(min_val))
self._slider.setMaximum(int(max_val))
self._slider.setSingleStep(int(step))
self._slider.setValue(int(default))
self._spin = QSpinBox()
self._spin.setMinimum(int(min_val))
self._spin.setMaximum(int(max_val))
self._spin.setSingleStep(int(step))
self._spin.setValue(int(default))
if suffix:
self._spin.setSuffix(suffix)
self._slider.valueChanged.connect(self._slider_moved_int)
self._spin.valueChanged.connect(self._spin_changed_int)
layout.addWidget(self._slider, 1)
self._spin.setFixedWidth(70)
self._spin.setAlignment(Qt.AlignmentFlag.AlignRight)
layout.addWidget(self._spin)
def _slider_moved_int(self, val: int):
if self._block_signals:
return
self._block_signals = True
self._spin.setValue(val)
self._block_signals = False
self.value_changed.emit(float(val))
def _spin_changed_int(self, val: int):
if self._block_signals:
return
self._block_signals = True
self._slider.setValue(val)
self._block_signals = False
self.value_changed.emit(float(val))
def _slider_moved_float(self, val: int):
if self._block_signals:
return
fval = val / self._scale
self._block_signals = True
self._spin.setValue(fval)
self._block_signals = False
self.value_changed.emit(fval)
def _spin_changed_float(self, val: float):
if self._block_signals:
return
self._block_signals = True
self._slider.setValue(int(val * self._scale))
self._block_signals = False
self.value_changed.emit(val)
def value(self) -> float:
if self._decimals > 0:
return self._spin.value()
return float(self._spin.value())
def set_value(self, val: float, emit: bool = True):
self._block_signals = True
if self._decimals > 0:
self._spin.setValue(val)
self._slider.setValue(int(val * self._scale))
else:
self._spin.setValue(int(val))
self._slider.setValue(int(val))
self._block_signals = False
if emit:
self.value_changed.emit(val)
def set_enabled(self, enabled: bool):
self._slider.setEnabled(enabled)
self._spin.setEnabled(enabled)
@@ -0,0 +1,109 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Preset bar for quick scene switching."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QHBoxLayout, QPushButton, QSizePolicy, QMenu, QInputDialog,
)
from ..theme import COLOR_ACCENT, COLOR_BG_INPUT, COLOR_BORDER, COLOR_TEXT_PRIMARY, COLOR_TEXT_SECONDARY
class PresetBar(QWidget):
"""Horizontal bar with preset buttons and an add button."""
preset_selected = Signal(str)
save_requested = Signal()
preset_deleted = Signal(str)
preset_renamed = Signal(str, str)
def __init__(self, parent=None):
super().__init__(parent)
self._presets: list[str] = []
self._active: str | None = None
self._buttons: dict[str, QPushButton] = {}
self._layout = QHBoxLayout(self)
self._layout.setContentsMargins(0, 4, 0, 4)
self._layout.setSpacing(4)
self._add_btn = QPushButton("+")
self._add_btn.setFixedSize(28, 28)
self._add_btn.setCursor(Qt.CursorShape.PointingHandCursor)
self._add_btn.setToolTip("Save new preset")
self._add_btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_BG_INPUT}; color: {COLOR_TEXT_SECONDARY};
border: 1px solid {COLOR_BORDER}; border-radius: 4px; font-size: 16px; font-weight: bold; }}
QPushButton:hover {{ color: {COLOR_TEXT_PRIMARY}; border-color: {COLOR_ACCENT}; }}
""")
self._add_btn.clicked.connect(self.save_requested.emit)
self._layout.addStretch()
self._layout.addWidget(self._add_btn)
def set_presets(self, names: list[str], active: str | None = None):
for btn in self._buttons.values():
self._layout.removeWidget(btn)
btn.deleteLater()
self._buttons.clear()
self._presets = list(names)
self._active = active
insert_pos = 0
for name in names:
btn = self._make_button(name)
self._layout.insertWidget(insert_pos, btn)
self._buttons[name] = btn
insert_pos += 1
self._apply_styles()
def _make_button(self, name: str) -> QPushButton:
btn = QPushButton(name)
btn.setFixedHeight(28)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
btn.clicked.connect(lambda: self._select(name))
btn.customContextMenuRequested.connect(lambda pos, n=name: self._context_menu(n, pos))
return btn
def _select(self, name: str):
self._active = name
self._apply_styles()
self.preset_selected.emit(name)
def _context_menu(self, name: str, pos):
menu = QMenu(self)
rename_action = menu.addAction("Rename")
delete_action = menu.addAction("Delete")
action = menu.exec(self._buttons[name].mapToGlobal(pos))
if action == rename_action:
new_name, ok = QInputDialog.getText(self, "Rename Preset", "New name:", text=name)
if ok and new_name and new_name != name:
self.preset_renamed.emit(name, new_name)
elif action == delete_action:
self.preset_deleted.emit(name)
def _apply_styles(self):
for name, btn in self._buttons.items():
active = (name == self._active)
if active:
btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_ACCENT}; color: {COLOR_TEXT_PRIMARY};
border: none; border-radius: 4px; font-weight: bold; padding: 2px 10px; }}
""")
else:
btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_BG_INPUT}; color: {COLOR_TEXT_SECONDARY};
border: 1px solid {COLOR_BORDER}; border-radius: 4px; padding: 2px 10px; }}
QPushButton:hover {{ color: {COLOR_TEXT_PRIMARY}; border-color: {COLOR_ACCENT}; }}
""")
@@ -0,0 +1,126 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Segmented button control for mutually exclusive options."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QPushButton, QSizePolicy
from PySide6.QtGui import QFont
from ..theme import COLOR_ACCENT, COLOR_BG_INPUT, COLOR_BORDER, COLOR_TEXT_PRIMARY, COLOR_TEXT_SECONDARY
class SegmentButton(QWidget):
"""Row of exclusive buttons styled as a segmented control."""
selection_changed = Signal(int)
selection_changed_text = Signal(str)
def __init__(self, options: list[str], parent=None):
super().__init__(parent)
self._options = options
self._buttons: list[QPushButton] = []
self._selected = 0
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setStyleSheet(f"""
SegmentButton {{
background: {COLOR_BG_INPUT};
border: 1px solid {COLOR_BORDER};
border-radius: 6px;
}}
""")
for i, label in enumerate(options):
btn = QPushButton(label)
btn.setCheckable(True)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
btn.setFixedHeight(28)
btn.clicked.connect(lambda checked, idx=i: self._on_click(idx))
self._buttons.append(btn)
layout.addWidget(btn)
self._apply_styles()
def _apply_styles(self):
for i, btn in enumerate(self._buttons):
active = (i == self._selected)
radius_left = "6px" if i == 0 else "0px"
radius_right = "6px" if i == len(self._buttons) - 1 else "0px"
if active:
btn.setStyleSheet(f"""
QPushButton {{
background-color: {COLOR_ACCENT};
color: {COLOR_TEXT_PRIMARY};
border: none;
border-radius: 0px;
border-top-left-radius: {radius_left};
border-bottom-left-radius: {radius_left};
border-top-right-radius: {radius_right};
border-bottom-right-radius: {radius_right};
font-weight: bold;
font-size: 12px;
padding: 2px 8px;
}}
""")
else:
btn.setStyleSheet(f"""
QPushButton {{
background-color: transparent;
color: {COLOR_TEXT_SECONDARY};
border: none;
border-radius: 0px;
border-top-left-radius: {radius_left};
border-bottom-left-radius: {radius_left};
border-top-right-radius: {radius_right};
border-bottom-right-radius: {radius_right};
font-size: 12px;
padding: 2px 8px;
}}
QPushButton:hover {{
color: {COLOR_TEXT_PRIMARY};
background-color: rgba(255,255,255,0.05);
}}
""")
btn.setChecked(active)
def _on_click(self, index: int):
if index == self._selected:
return
self._selected = index
self._apply_styles()
self.selection_changed.emit(index)
self.selection_changed_text.emit(self._options[index])
def selected_index(self) -> int:
return self._selected
def selected_text(self) -> str:
return self._options[self._selected]
def set_selected(self, index: int, emit: bool = True):
if index < 0 or index >= len(self._options):
return
if index == self._selected:
return
self._selected = index
self._apply_styles()
if emit:
self.selection_changed.emit(index)
self.selection_changed_text.emit(self._options[index])
@@ -0,0 +1,95 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""iOS-style toggle switch widget."""
from PySide6.QtCore import Qt, Signal, QPropertyAnimation, QEasingCurve, Property, QRectF
from PySide6.QtWidgets import QWidget
from PySide6.QtGui import QPainter, QColor
from ..theme import COLOR_ACCENT, COLOR_TOGGLE_OFF
class ToggleSwitch(QWidget):
"""Custom painted toggle switch. Pink when on, gray when off."""
toggled = Signal(bool)
TRACK_W = 44
TRACK_H = 22
THUMB_RADIUS = 8
THUMB_MARGIN = 3
def __init__(self, checked: bool = False, parent=None):
super().__init__(parent)
self._checked = checked
self._thumb_pos = float(self.TRACK_W - self.THUMB_MARGIN - self.THUMB_RADIUS
if checked
else self.THUMB_MARGIN + self.THUMB_RADIUS)
self.setFixedSize(self.TRACK_W, self.TRACK_H)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self._anim = QPropertyAnimation(self, b"thumb_pos")
self._anim.setDuration(150)
self._anim.setEasingCurve(QEasingCurve.Type.InOutQuad)
def _get_thumb_pos(self) -> float:
return self._thumb_pos
def _set_thumb_pos(self, val: float):
self._thumb_pos = val
self.update()
thumb_pos = Property(float, _get_thumb_pos, _set_thumb_pos)
def is_checked(self) -> bool:
return self._checked
def set_checked(self, checked: bool, emit: bool = True):
if self._checked == checked:
return
self._checked = checked
target = (self.TRACK_W - self.THUMB_MARGIN - self.THUMB_RADIUS
if checked
else self.THUMB_MARGIN + self.THUMB_RADIUS)
self._anim.stop()
self._anim.setStartValue(self._thumb_pos)
self._anim.setEndValue(float(target))
self._anim.start()
if emit:
self.toggled.emit(checked)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.set_checked(not self._checked)
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
track_color = QColor(COLOR_ACCENT) if self._checked else QColor(COLOR_TOGGLE_OFF)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(track_color)
p.drawRoundedRect(QRectF(0, 0, self.TRACK_W, self.TRACK_H),
self.TRACK_H / 2, self.TRACK_H / 2)
p.setBrush(QColor("#ffffff"))
p.drawEllipse(QRectF(self._thumb_pos - self.THUMB_RADIUS,
(self.TRACK_H - 2 * self.THUMB_RADIUS) / 2,
2 * self.THUMB_RADIUS, 2 * self.THUMB_RADIUS))
p.end()
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+16
View File
@@ -0,0 +1,16 @@
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "yolocam"
version = "0.1.0"
description = "YoloCam S3 control protocol library"
license = "GPL-3.0-or-later"
requires-python = ">=3.10"
dependencies = [
"protobuf>=4.0",
]
[tool.setuptools.packages.find]
include = ["yolocam*"]
+70
View File
@@ -0,0 +1,70 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""YoloCam S3 control protocol library.
Provides wire format encoding, parameter definitions, and a thread-safe TCP
client for the YoloCam S3 camera's protobuf control protocol.
"""
from .client import YoloCamClient
from .params import (
PARAMS, ParamDef, PARAM_CATEGORIES,
ISO_VALUES, SHUTTER_TABLE, SHUTTER_REVERSE, APERTURE_TABLE,
ZOOM_RAW_MIN, ZOOM_RAW_MAX, ZOOM_MULT_MIN, ZOOM_MULT_MAX,
zoom_raw_to_mult, zoom_mult_to_raw,
sharpness_to_wire, sharpness_from_wire,
format_value, format_shutter, format_aperture, format_zoom,
find_nearest_aperture,
is_readable, is_writable,
)
from .color import rgb_to_cct
from .protocol import (
CAMERA_IP, CAMERA_PORT, DEFAULT_TIMEOUT,
pack_frame, unpack_frame, xor_checksum,
)
__all__ = [
"YoloCamClient",
"PARAMS",
"ParamDef",
"PARAM_CATEGORIES",
"ISO_VALUES",
"SHUTTER_TABLE",
"SHUTTER_REVERSE",
"APERTURE_TABLE",
"ZOOM_RAW_MIN",
"ZOOM_RAW_MAX",
"ZOOM_MULT_MIN",
"ZOOM_MULT_MAX",
"zoom_raw_to_mult",
"zoom_mult_to_raw",
"sharpness_to_wire",
"sharpness_from_wire",
"format_value",
"format_shutter",
"format_aperture",
"format_zoom",
"find_nearest_aperture",
"is_readable",
"is_writable",
"CAMERA_IP",
"CAMERA_PORT",
"DEFAULT_TIMEOUT",
"pack_frame",
"unpack_frame",
"xor_checksum",
"rgb_to_cct",
]
+780
View File
@@ -0,0 +1,780 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Thread-safe camera client for the YoloCam S3.
Provides a high-level interface for getting/setting camera parameters over the
TCP protobuf control protocol. Network I/O runs in a background thread.
Override the _on_*() hook methods in subclasses to integrate with event systems
(e.g. Qt signals, asyncio callbacks).
"""
import logging
import socket
import struct
import threading
import time
from typing import Any, Dict, Optional
from . import yolocam_pb2 as pb
from .params import (
PARAMS, ParamDef, format_value, is_readable, is_writable,
zoom_mult_to_raw, zoom_raw_to_mult,
SHUTTER_TABLE, SHUTTER_REVERSE, APERTURE_TABLE,
)
from .protocol import (
CAMERA_IP, CAMERA_PORT, DEFAULT_TIMEOUT, OUTER_HEADER_LEN, OUTER_START_FLAG,
MIN_REQUEST_INTERVAL, HEARTBEAT_INTERVAL, RECONNECT_THRESHOLD, REQUEST_TIMEOUT_MS,
pack_frame, unpack_frame,
)
log = logging.getLogger(__name__)
class YoloCamClient:
"""High-level, thread-safe camera client.
All network I/O is serialized through an internal lock. The heartbeat runs
on a daemon thread. Override the _on_*() hook methods to receive state
change notifications.
"""
def __init__(
self,
ip: str = CAMERA_IP,
port: int = CAMERA_PORT,
timeout: float = DEFAULT_TIMEOUT,
):
self.ip = ip
self.port = port
self.timeout = timeout
self._sock: Optional[socket.socket] = None
self._seq = 0
self._lock = threading.Lock()
self._heartbeat_thread: Optional[threading.Thread] = None
self._heartbeat_stop = threading.Event()
self._last_request_time = 0.0
self._connection_state = "disconnected"
@property
def connection_state(self) -> str:
return self._connection_state
# -- Hook methods for subclass override --
def _on_connected(self) -> None:
"""Called after successful connection."""
pass
def _on_disconnected(self) -> None:
"""Called after disconnection."""
pass
def _on_error(self, message: str) -> None:
"""Called when an error occurs."""
pass
def _on_param_changed(self, name: str, value: Any) -> None:
"""Called when a parameter value is read or set successfully."""
pass
def _on_recording_state_changed(self, recording: bool) -> None:
"""Called when recording state changes."""
pass
def _on_recording_duration_changed(self, duration: int) -> None:
"""Called when recording duration updates via NOTIFY."""
pass
# -- Connection management --
def connect(self) -> None:
"""Open TCP connection to the camera and start heartbeat."""
self._connection_state = "connecting"
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect((self.ip, self.port))
self._sock = sock
self._connection_state = "connected"
log.info("Connected to camera at %s:%d", self.ip, self.port)
self._on_connected()
self._start_heartbeat()
except (socket.error, OSError) as exc:
self._connection_state = "disconnected"
msg = f"Connection failed: {exc}"
log.error(msg)
self._on_error(msg)
raise
def disconnect(self) -> None:
"""Close the connection and stop heartbeat."""
self._heartbeat_stop.set()
# Force-shutdown the socket to unblock any thread stuck in recv().
# Must happen BEFORE acquiring _lock since the thread holding it
# may be blocked waiting on the socket.
sock = self._sock
if sock:
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
if self._heartbeat_thread:
self._heartbeat_thread.join(timeout=2)
self._heartbeat_thread = None
with self._lock:
if self._sock:
try:
self._sock.close()
except OSError:
pass
self._sock = None
self._connection_state = "disconnected"
log.info("Disconnected from camera")
self._on_disconnected()
# Aliases for backward compatibility
open = connect
close = disconnect
def reopen(self) -> None:
"""Drop and re-establish the connection."""
log.info("Reconnecting to camera...")
try:
self.disconnect()
except Exception:
pass
time.sleep(0.5)
self.connect()
# -- Parameter access --
def get_param(self, name: str) -> Optional[str]:
"""Read a parameter and return its formatted display value.
Returns None if the parameter is set-only or the camera did not respond.
"""
pdef = PARAMS.get(name)
if pdef is None:
self._on_error(f"Unknown parameter: {name}")
return None
if not is_readable(pdef):
return None
with self._lock:
try:
resp = self._request(pdef.cid)
except socket.timeout:
log.warning("Timeout reading %s", name)
return None
except Exception as exc:
self._on_error(f"Error reading {name}: {exc}")
return None
if resp is None:
return None
raw = self._extract_int_value(resp)
if raw is not None:
formatted = format_value(name, raw)
self._on_param_changed(name, raw)
return formatted
# Non-integer response types (version_info, exposure_params, etc.)
return self._format_complex_response(resp, name)
def get_param_raw(self, name: str) -> Optional[int]:
"""Read a parameter and return the raw integer value."""
pdef = PARAMS.get(name)
if pdef is None or not is_readable(pdef):
return None
with self._lock:
try:
resp = self._request(pdef.cid)
except Exception:
return None
if resp is None:
return None
return self._extract_int_value(resp)
def set_param(self, name: str, value: Any) -> bool:
"""Set a parameter. Returns True on success (resp_code 200)."""
pdef = PARAMS.get(name)
if pdef is None:
self._on_error(f"Unknown parameter: {name}")
return False
if not is_writable(pdef):
self._on_error(f"Parameter '{name}' is read-only")
return False
if name == "zoom":
raw = zoom_mult_to_raw(float(value))
else:
raw = int(value)
with self._lock:
try:
resp = self._set_int(pdef.cid, raw)
except Exception as exc:
self._on_error(f"Error setting {name}: {exc}")
return False
if resp is None:
return False
success = resp.resp_code == 200
if success:
self._on_param_changed(name, raw)
return success
def get_all_params(self) -> Dict[str, Any]:
"""Read all readable parameters, reconnecting after consecutive timeouts."""
results: Dict[str, Any] = {}
consecutive_timeouts = 0
for name, pdef in PARAMS.items():
if not is_readable(pdef):
continue
with self._lock:
try:
resp = self._request(pdef.cid, recv_timeout=3.0)
raw = self._extract_int_value(resp) if resp else None
results[name] = raw
consecutive_timeouts = 0
except socket.timeout:
results[name] = None
consecutive_timeouts += 1
if consecutive_timeouts >= RECONNECT_THRESHOLD:
self._reconnect_socket()
consecutive_timeouts = 0
except Exception as exc:
log.warning("Error reading %s: %s", name, exc)
results[name] = None
return results
# -- Compound commands --
def set_wb_offset(self, red: int, blue: int) -> bool:
"""Set white balance offset using compound WhiteBalanceOffset message."""
with self._lock:
self._throttle()
msg = pb.Message()
msg.type = pb.TYPE_SET
msg.seq = self._next_seq()
msg.timeout = REQUEST_TIMEOUT_MS
msg.id = pb.CID_WHITE_BALANCE_OFFSET
msg.body.white_balance_offset.offset_r = red
msg.body.white_balance_offset.offset_b = blue
try:
self._send_message(msg)
resp = self._recv_message()
return resp is not None and resp.resp_code == 200
except Exception as exc:
self._on_error(f"Error setting WB offset: {exc}")
return False
def start_recording(self) -> bool:
"""Start recording to SD card."""
with self._lock:
try:
resp = self._set_int(pb.CID_RECORDING_START, 1)
except Exception as exc:
self._on_error(f"Error starting recording: {exc}")
return False
success = resp is not None and resp.resp_code == 200
if success:
self._on_recording_state_changed(True)
return success
def stop_recording(self) -> bool:
"""Stop recording."""
with self._lock:
try:
resp = self._set_int(pb.CID_RECORDING_STOP, 1)
except Exception as exc:
self._on_error(f"Error stopping recording: {exc}")
return False
success = resp is not None and resp.resp_code == 200
if success:
self._on_recording_state_changed(False)
return success
def set_ai_tracking(self, mode: int) -> bool:
"""Set AI tracking mode (0=Portrait, 1=Thing, 2=Off)."""
with self._lock:
self._throttle()
msg = pb.Message()
msg.type = pb.TYPE_SET
msg.seq = self._next_seq()
msg.timeout = REQUEST_TIMEOUT_MS
msg.id = pb.CID_AI_TRACKING_CTRL
msg.body.ai_tracking_ctrl.mode = mode
try:
self._send_message(msg)
resp = self._recv_message()
return resp is not None and resp.resp_code == 200
except Exception as exc:
self._on_error(f"Error setting AI tracking: {exc}")
return False
def set_clut_enabled(self, enabled: bool) -> bool:
"""Enable or disable color LUT."""
with self._lock:
try:
resp = self._set_int(pb.CID_ENABLE_CLUT, 1 if enabled else 0)
except Exception as exc:
self._on_error(f"Error setting CLUT: {exc}")
return False
return resp is not None and resp.resp_code == 200
def set_clut_attr(self, value: int) -> bool:
"""Set CLUT attribute/intensity (0-255)."""
with self._lock:
try:
resp = self._set_int(pb.CID_CLUT_ATTR, value)
except Exception as exc:
self._on_error(f"Error setting CLUT attr: {exc}")
return False
return resp is not None and resp.resp_code == 200
def send_clut(self, clut_data: list, hsv_data: str = "{}",
extra: str = "", updataflag: str = "0") -> bool:
"""Send a 5508-entry CLUT to the camera.
clut_data: list of 5508 uint32 values (packed 10-bit RGB deltas)
hsv_data: JSON string of HSV grid state for round-trip fidelity
extra: mode identifier ("pro", "origin", or JSON drag history)
updataflag: "0" for user edit, "1" for preset
"""
with self._lock:
self._throttle()
msg = pb.Message()
msg.type = pb.TYPE_SET
msg.seq = self._next_seq()
msg.timeout = REQUEST_TIMEOUT_MS
msg.id = pb.CID_CLUT_FILE
msg.body.tuning_clut_file.clut_size = len(clut_data)
msg.body.tuning_clut_file.clut_data.extend(clut_data)
msg.body.tuning_clut_file.hsv_data = hsv_data
msg.body.tuning_clut_file.extra = extra
msg.body.tuning_clut_file.updataflag = updataflag
try:
self._send_message(msg)
resp = self._recv_message()
return resp is not None and resp.resp_code == 200
except Exception as exc:
self._on_error(f"Error sending CLUT: {exc}")
return False
def reset_clut(self) -> bool:
"""Send an identity (all-zero) CLUT to reset color grading."""
return self.send_clut([0] * 5508)
def set_tuning(self, brightness: int, curve: float, color_temp: int) -> bool:
"""Set image tuning parameters."""
with self._lock:
self._throttle()
msg = pb.Message()
msg.type = pb.TYPE_SET
msg.seq = self._next_seq()
msg.timeout = REQUEST_TIMEOUT_MS
msg.id = pb.CID_TUNING
msg.body.tuning_param.brightness = brightness
msg.body.tuning_param.curve = curve
msg.body.tuning_param.color_temp = color_temp
try:
self._send_message(msg)
resp = self._recv_message()
return resp is not None and resp.resp_code == 200
except Exception as exc:
self._on_error(f"Error setting tuning: {exc}")
return False
def format_sd_card(self) -> bool:
"""Format the SD card."""
with self._lock:
try:
resp = self._set_int(pb.CID_DISK_FORMAT, 1)
except Exception as exc:
self._on_error(f"Error formatting SD card: {exc}")
return False
return resp is not None and resp.resp_code == 200
def set_exposure(
self,
iso: Optional[int] = None,
shutter_us: Optional[int] = None,
aperture: Optional[int] = None,
) -> Optional[pb.Message]:
"""Send manual exposure parameters as a compound message."""
with self._lock:
self._throttle()
msg = pb.Message()
msg.type = pb.TYPE_SET
msg.seq = self._next_seq()
msg.timeout = REQUEST_TIMEOUT_MS
msg.id = pb.CID_EXPOSURE_MODE
params = pb.ManualExposureParams()
if iso is not None:
params.iso = iso
if shutter_us is not None:
params.shutter = shutter_us
if aperture is not None:
params.aperture = aperture
msg.body.exposure_params.CopyFrom(params)
self._send_message(msg)
return self._recv_message()
# -- Raw protocol access --
def request(self, command_id: int, recv_timeout: Optional[float] = None) -> Optional[pb.Message]:
"""Send a raw REQUEST and return the parsed response."""
with self._lock:
return self._request(command_id, recv_timeout)
def set_int(self, command_id: int, value: int) -> Optional[pb.Message]:
"""Send a raw SET command with an integer value."""
with self._lock:
return self._set_int(command_id, value)
def start_heartbeat(self) -> None:
"""Start the heartbeat thread (if not already running)."""
if self._heartbeat_thread and self._heartbeat_thread.is_alive():
return
self._start_heartbeat()
def stop_heartbeat(self) -> None:
"""Stop the heartbeat thread."""
self._stop_heartbeat()
# -- Internal protocol methods (must be called with self._lock held) --
def _throttle(self) -> None:
"""Enforce minimum delay between requests to avoid overwhelming the camera."""
elapsed = time.monotonic() - self._last_request_time
if elapsed < MIN_REQUEST_INTERVAL:
time.sleep(MIN_REQUEST_INTERVAL - elapsed)
self._last_request_time = time.monotonic()
def _next_seq(self) -> int:
self._seq += 1
return self._seq
def _send_message(self, msg: pb.Message) -> None:
if self._sock is None:
raise ConnectionError("Not connected to camera")
payload = msg.SerializeToString()
frame = pack_frame(payload)
self._sock.sendall(frame)
_MAX_NOTIFY_DRAIN = 50
def _recv_message(self) -> Optional[pb.Message]:
"""Read the next non-NOTIFY message, dispatching any NOTIFYs encountered.
Caps the number of consecutive NOTIFYs drained to _MAX_NOTIFY_DRAIN to
prevent holding the lock indefinitely when the camera is streaming
high-frequency notifications (e.g. face bounding boxes at 30fps).
"""
for _ in range(self._MAX_NOTIFY_DRAIN):
msg = self._recv_one_message()
if msg is None:
return None
if msg.type == pb.TYPE_NOTIFY:
self._handle_notify(msg)
continue
return msg
log.warning("Exceeded NOTIFY drain limit (%d), giving up on response", self._MAX_NOTIFY_DRAIN)
return None
def _recv_one_message(self) -> Optional[pb.Message]:
if self._sock is None:
return None
outer = self._recv_exact(OUTER_HEADER_LEN)
if not outer:
return None
if outer[0] != OUTER_START_FLAG:
raise ValueError(f"Bad outer start flag: 0x{outer[0]:02x}")
inner_size = struct.unpack_from('<I', outer, 4)[0]
if inner_size <= 0 or inner_size > 1024 * 1024:
raise ValueError(f"Invalid inner_size: {inner_size}")
inner = self._recv_exact(inner_size)
if not inner:
return None
full_frame = outer + inner
proto_data = unpack_frame(full_frame)
resp = pb.Message()
resp.ParseFromString(proto_data)
return resp
_SILENT_NOTIFY_CIDS = frozenset({
pb.CID_FACE_BOUNDING_BOXES,
pb.CID_STREAM_HEARTBEAT,
})
def _handle_notify(self, msg: pb.Message) -> None:
"""Dispatch an unsolicited NOTIFY message from the camera."""
if msg.id == pb.CID_DURATION_CHANGED:
duration = self._extract_int_value(msg)
if duration is not None:
self._on_recording_duration_changed(duration)
else:
log.debug("NOTIFY CID_DURATION_CHANGED with no int_val")
elif msg.id == pb.CID_RECORDING_FINISHED:
self._on_recording_state_changed(False)
elif msg.id not in self._SILENT_NOTIFY_CIDS:
log.debug("Unhandled NOTIFY CID %d", msg.id)
def _recv_exact(self, n: int) -> Optional[bytes]:
if self._sock is None:
return None
buf = bytearray()
while len(buf) < n:
chunk = self._sock.recv(n - len(buf))
if not chunk:
return None
buf.extend(chunk)
return bytes(buf)
def _flush_recv_buffer(self) -> None:
if self._sock is None:
return
self._sock.setblocking(False)
try:
while True:
try:
data = self._sock.recv(4096)
if not data:
break
except BlockingIOError:
break
finally:
self._sock.setblocking(True)
self._sock.settimeout(self.timeout)
def _request(self, command_id: int, recv_timeout: Optional[float] = None) -> Optional[pb.Message]:
self._throttle()
msg = pb.Message()
msg.type = pb.TYPE_REQUEST
msg.seq = self._next_seq()
msg.timeout = REQUEST_TIMEOUT_MS
msg.id = command_id
if recv_timeout is not None and self._sock is not None:
self._sock.settimeout(recv_timeout)
try:
self._send_message(msg)
return self._recv_message()
except socket.timeout:
self._flush_recv_buffer()
raise
finally:
if recv_timeout is not None and self._sock is not None:
self._sock.settimeout(self.timeout)
def _set_int(self, command_id: int, value: int) -> Optional[pb.Message]:
self._throttle()
msg = pb.Message()
msg.type = pb.TYPE_SET
msg.seq = self._next_seq()
msg.timeout = REQUEST_TIMEOUT_MS
msg.id = command_id
msg.body.int_val = value
self._send_message(msg)
return self._recv_message()
def _reconnect_socket(self) -> None:
"""Low-level socket reconnect (no lock, no heartbeat management)."""
if self._sock:
try:
self._sock.close()
except OSError:
pass
time.sleep(0.5)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect((self.ip, self.port))
self._sock = sock
log.info("Socket reconnected")
# -- Heartbeat --
def _start_heartbeat(self) -> None:
self._heartbeat_stop.clear()
def heartbeat_loop() -> None:
while not self._heartbeat_stop.wait(HEARTBEAT_INTERVAL):
try:
with self._lock:
self._set_int(pb.CID_STREAM_HEARTBEAT, 1)
except Exception:
break
self._heartbeat_thread = threading.Thread(target=heartbeat_loop, daemon=True, name="yolocam-heartbeat")
self._heartbeat_thread.start()
def _stop_heartbeat(self) -> None:
self._heartbeat_stop.set()
if self._heartbeat_thread:
self._heartbeat_thread.join(timeout=2)
self._heartbeat_thread = None
# -- Response parsing helpers --
@staticmethod
def _extract_int_value(resp: pb.Message) -> Optional[int]:
if not resp.HasField("body"):
return None
body = resp.body
which = body.WhichOneof("value")
if which == "int_val":
return body.int_val
return None
def _format_complex_response(self, resp: pb.Message, name: str) -> Optional[str]:
"""Format non-integer response bodies into display strings."""
if not resp.HasField("body"):
return None
body = resp.body
which = body.WhichOneof("value")
if which == "version_info":
vi = body.version_info
return f"{vi.sys_version} (S/N: {vi.serial_num})"
if which == "exposure_params":
ep = body.exposure_params
parts = [f"ISO {ep.iso}"]
if ep.shutter in SHUTTER_REVERSE:
parts.append(f"1/{SHUTTER_REVERSE[ep.shutter]}s")
else:
parts.append(f"{ep.shutter}us")
if ep.aperture in APERTURE_TABLE:
parts.append(APERTURE_TABLE[ep.aperture])
return ", ".join(parts)
if which == "range":
return f"{body.range.min}-{body.range.max}"
if which == "lens_detail":
ld = body.lens_detail
return f"ID:{ld.lens_id} {APERTURE_TABLE.get(ld.aperture, '')} focal:{ld.focal}"
if which == "disk_info":
di = body.disk_info
return f"{di.available_size}/{di.total_size}MB"
if which == "lens_version_info":
lvi = body.lens_version_info
return f"{lvi.current_version}"
if which == "video_status":
return str(body.video_status.status)
if which == "stream_param":
sp = body.stream_param
if sp.HasField("venc_param"):
v = sp.venc_param
return f"{v.width}x{v.height}@{v.rate}fps"
return "stream config"
if which == "str_val":
return body.str_val
return str(which)
+458
View File
@@ -0,0 +1,458 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""HSV-to-CLUT conversion for the YoloCam S3 HiSilicon ISP 3D color LUT.
The ISP uses a 17x17x17 3D LUT stored as 5508 uint32 entries in an interleaved
octant layout. Each uint32 packs three signed 10-bit RGB delta values.
Two modes produce CLUTs:
Fast mode -- a [24][12] grid of absolute (theta, r_norm) polar positions modified
by a two-point drag with linear falloff
Professional mode -- a [9][12][25] grid of delta/scale HSV adjustments from
per-point dragging
The HSV adjustment grid is 3 channels (hue/saturation/luma) each shaped [9][12][25],
representing 9 luma levels, 12 saturation columns, and 25 hue rows (24 sectors of
15 degrees, with row 24 wrapping to row 0).
"""
import colorsys
import copy
from typing import List, Tuple
CLUT_SIZE = 5508
GRID_DIM = 17
HUE_SECTORS = 24
SAT_COLUMNS = 12
LUMA_LEVELS = 9
FULL_R_VALUE = 1.17
LINE_CENTER = 0
LINE_LEFT = 1
LINE_RIGHT = 2
INTERVAL_THETA = 360.0 / HUE_SECTORS
INTERVAL_R_NORM = FULL_R_VALUE / (SAT_COLUMNS - 1)
# Per-octant base offsets in the interleaved 5508-entry array.
# Octant = (x&1) + ((y&1)<<1) + ((z&1)<<2). For dim=17 (9 even, 8 odd values per axis):
# octant 0: 9*9*9=729, octant 1: 8*9*9=648, ..., octant 7: 8*8*8=512
_OCTANT_SIZES = [729, 648, 648, 576, 648, 576, 576, 512]
_OCTANT_BASES = []
_base = 0
for _sz in _OCTANT_SIZES:
_OCTANT_BASES.append(_base)
_base += _sz
def identity_clut() -> List[int]:
"""Return a 5508-entry all-zeros CLUT (identity / no-op)."""
return [0] * CLUT_SIZE
def pack_clut(rgb_deltas: List[List[List[List[float]]]]) -> List[int]:
"""Pack [3][17][17][17] float RGB deltas into 5508 interleaved uint32 entries.
Each float is a fractional delta in [-1.0, ~1.0). Values are quantized to 10-bit
signed integers (s0.9 fixed-point, divided by 512 on the ISP) and packed as
(R << 20) | (G << 10) | B.
"""
data = [0] * CLUT_SIZE
counters = [0] * 8
for x in range(GRID_DIM):
for y in range(GRID_DIM):
for z in range(GRID_DIM):
octant = (x & 1) + ((y & 1) << 1) + ((z & 1) << 2)
idx = _OCTANT_BASES[octant] + counters[octant]
counters[octant] += 1
r = _clamp_and_quantize(rgb_deltas[0][x][y][z])
g = _clamp_and_quantize(rgb_deltas[1][x][y][z])
b = _clamp_and_quantize(rgb_deltas[2][x][y][z])
data[idx] = (r << 20) | (g << 10) | b
return data
def unpack_clut(data: List[int]) -> List[List[List[List[float]]]]:
"""Unpack 5508 interleaved uint32 entries into [3][17][17][17] float RGB deltas."""
if len(data) < CLUT_SIZE:
raise ValueError(f"Expected {CLUT_SIZE} entries, got {len(data)}")
result = [[[[0.0] * GRID_DIM for _ in range(GRID_DIM)] for _ in range(GRID_DIM)] for _ in range(3)]
counters = [0] * 8
for x in range(GRID_DIM):
for y in range(GRID_DIM):
for z in range(GRID_DIM):
octant = (x & 1) + ((y & 1) << 1) + ((z & 1) << 2)
idx = _OCTANT_BASES[octant] + counters[octant]
counters[octant] += 1
val = data[idx]
b = val & 0x3FF
g = (val >> 10) & 0x3FF
r = (val >> 20) & 0x3FF
r = (r - 1024) if (r & 0x200) else r
g = (g - 1024) if (g & 0x200) else g
b = (b - 1024) if (b & 0x200) else b
result[0][x][y][z] = r / 512.0
result[1][x][y][z] = g / 512.0
result[2][x][y][z] = b / 512.0
return result
def make_hsv_grid() -> Tuple[List, List, List]:
"""Return identity HSV adjustment grids (hue=0, sat=1.0, luma=0).
Returns (hue_grid, sat_grid, luma_grid) each shaped [9][12][25].
"""
hue_grid = [[[0.0] * (HUE_SECTORS + 1) for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
sat_grid = [[[1.0] * (HUE_SECTORS + 1) for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
luma_grid = [[[0.0] * (HUE_SECTORS + 1) for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
return hue_grid, sat_grid, luma_grid
def hsv_grid_to_clut(
hue_grid: List[List[List[float]]],
sat_grid: List[List[List[float]]],
luma_grid: List[List[List[float]]],
) -> List[int]:
"""Convert [9][12][25] HSV adjustment grids into a 5508-entry uint32 CLUT.
hue_grid values are degree offsets, sat_grid values are scale factors
(0=desaturate, 1=no change, >1=boost), luma_grid values are brightness offsets.
"""
rgb_deltas = [[[[0.0] * GRID_DIM for _ in range(GRID_DIM)] for _ in range(GRID_DIM)] for _ in range(3)]
for ri in range(GRID_DIM):
for gi in range(GRID_DIM):
for bi in range(GRID_DIM):
r_norm = ri / 16.0
g_norm = gi / 16.0
b_norm = bi / 16.0
h, s, v = _rgb_to_hsv(r_norm, g_norm, b_norm)
hue_adj, sat_adj, luma_adj = _lookup_hsv_adjustment(h, s, v, hue_grid, sat_grid, luma_grid)
h_new = (h + hue_adj / 360.0) % 1.0
s_new = max(0.0, min(1.0, s * sat_adj))
v_new = max(0.0, min(1.0, v + luma_adj))
r_new, g_new, b_new = colorsys.hsv_to_rgb(h_new, s_new, v_new)
rgb_deltas[0][ri][gi][bi] = r_new - r_norm
rgb_deltas[1][ri][gi][bi] = g_new - g_norm
rgb_deltas[2][ri][gi][bi] = b_new - b_norm
return pack_clut(rgb_deltas)
def _clamp_and_quantize(value: float) -> int:
"""Quantize a float delta to a 10-bit two's complement unsigned representation.
The ISP interprets 10-bit values as s0.9 fixed-point (divide by 512), giving
a range of [-1.0, 0.998]. We multiply by 512 to match that encoding.
"""
quantized = round(value * 512)
quantized = max(-512, min(511, quantized))
if quantized < 0:
quantized += 1024
return quantized
def _rgb_to_hsv(r: float, g: float, b: float) -> Tuple[float, float, float]:
"""Convert RGB [0,1] to HSV where H is [0,1), S is [0,1], V is [0,1]."""
return colorsys.rgb_to_hsv(r, g, b)
def _lookup_hsv_adjustment(
h: float, s: float, v: float,
hue_grid: List[List[List[float]]],
sat_grid: List[List[List[float]]],
luma_grid: List[List[List[float]]],
) -> Tuple[float, float, float]:
"""Trilinearly interpolate HSV adjustments from the 9x12x25 grids."""
hue_pos = h * HUE_SECTORS
sat_pos = s * (SAT_COLUMNS - 1) * (1.0 / FULL_R_VALUE) if FULL_R_VALUE > 0 else 0.0
luma_pos = v * (LUMA_LEVELS - 1)
hue_idx = int(hue_pos)
hue_frac = hue_pos - hue_idx
hue_idx = hue_idx % HUE_SECTORS
sat_idx = min(int(sat_pos), SAT_COLUMNS - 2)
sat_frac = max(0.0, min(1.0, sat_pos - sat_idx))
luma_idx = min(int(luma_pos), LUMA_LEVELS - 2)
luma_frac = max(0.0, min(1.0, luma_pos - luma_idx))
hue_idx_next = (hue_idx + 1) % HUE_SECTORS
hue_adj = _trilinear(hue_grid, luma_idx, sat_idx, hue_idx, hue_idx_next, luma_frac, sat_frac, hue_frac)
sat_adj = _trilinear(sat_grid, luma_idx, sat_idx, hue_idx, hue_idx_next, luma_frac, sat_frac, hue_frac)
luma_adj = _trilinear(luma_grid, luma_idx, sat_idx, hue_idx, hue_idx_next, luma_frac, sat_frac, hue_frac)
return hue_adj, sat_adj, luma_adj
def _trilinear(
grid: List[List[List[float]]],
li: int, si: int, hi: int, hi_next: int,
lf: float, sf: float, hf: float,
) -> float:
"""Trilinear interpolation across luma, saturation, and hue axes."""
def sample(l: int, s: int, h: int) -> float:
return grid[l][s][h]
c000 = sample(li, si, hi)
c001 = sample(li, si, hi_next)
c010 = sample(li, si + 1, hi)
c011 = sample(li, si + 1, hi_next)
c100 = sample(li + 1, si, hi)
c101 = sample(li + 1, si, hi_next)
c110 = sample(li + 1, si + 1, hi)
c111 = sample(li + 1, si + 1, hi_next)
c00 = c000 + (c001 - c000) * hf
c01 = c010 + (c011 - c010) * hf
c10 = c100 + (c101 - c100) * hf
c11 = c110 + (c111 - c110) * hf
c0 = c00 + (c01 - c00) * sf
c1 = c10 + (c11 - c10) * sf
return c0 + (c1 - c0) * lf
# ---------------------------------------------------------------------------
# Fast mode: two-point color remapping via absolute polar grid
# ---------------------------------------------------------------------------
def init_fast_grid() -> List[List[List[float]]]:
"""Return identity Fast mode grid [24][12] of [theta_deg, r_norm]."""
grid = []
for h in range(HUE_SECTORS):
row = []
for s in range(SAT_COLUMNS):
theta = h * INTERVAL_THETA
r_norm = s * INTERVAL_R_NORM
row.append([round(theta, 3), round(r_norm, 3)])
grid.append(row)
return grid
def init_luma_grid() -> List[List[float]]:
"""Return all-zeros luma grid [24][12]."""
return [[0.0] * SAT_COLUMNS for _ in range(HUE_SECTORS)]
def calc_rows_data(
line_num: int, col_num: int,
dest_theta: float, dest_r_norm: float,
grid: List[List[List[float]]],
) -> None:
"""Apply a two-point color shift to the Fast mode grid (in place).
Computes the delta between the source grid point's origin position and the
destination, then propagates the shift across the center hue row and both
neighbors with linear falloff.
line_num, col_num: source grid indices
dest_theta: destination angle in degrees [0, 360)
dest_r_norm: destination normalized radius (clamped to FULL_R_VALUE)
grid: [24][12] of [theta, r_norm], modified in place
"""
dest_r_norm = min(dest_r_norm, 1.0)
origin_theta = line_num * INTERVAL_THETA
origin_r_norm = col_num * INTERVAL_R_NORM
theta_delta = dest_theta - origin_theta
if theta_delta > 180:
theta_delta -= 360
if theta_delta < -180:
theta_delta += 360
r_delta = dest_r_norm - origin_r_norm
_pull_line(line_num, col_num, r_delta, theta_delta, LINE_CENTER, grid)
_pull_line(line_num, col_num, r_delta, theta_delta, LINE_LEFT, grid)
_pull_line(line_num, col_num, r_delta, theta_delta, LINE_RIGHT, grid)
def _pull_line(
line_num: int, col_num: int,
r_delta: float, theta_delta: float,
direction: int,
grid: List[List[List[float]]],
) -> None:
"""Propagate a shift across one hue row with linear falloff.
For each saturation column (skipping center), the shift decays by 11%/step
for theta and 12%/step for radius based on distance from the source column.
The outermost column receives no radial shift. LEFT/RIGHT rows get half shift.
"""
row = line_num
if direction == LINE_LEFT:
row = (line_num - 1) % HUE_SECTORS
elif direction == LINE_RIGHT:
row = (line_num + 1) % HUE_SECTORS
for col in range(1, SAT_COLUMNS):
dist = abs(col - col_num)
if dist >= 9:
dist = 9
theta_shift = theta_delta * (1.0 - 0.11 * dist)
r_shift = 0.0
if col < SAT_COLUMNS - 1:
r_shift = r_delta * (1.0 - 0.12 * dist)
if direction != LINE_CENTER:
theta_shift /= 2.0
r_shift /= 2.0
base_theta = row * INTERVAL_THETA
base_r_norm = col * INTERVAL_R_NORM
grid[row][col] = [
round(base_theta + theta_shift, 3),
round(max(0.0, base_r_norm + r_shift), 3),
]
def fast_grid_to_clut(
grid: List[List[List[float]]],
luma: List[List[float]] = None,
) -> List[int]:
"""Convert a Fast mode [24][12] absolute-position grid to a 5508-entry CLUT.
grid[h][s] = [theta_deg, r_norm] (absolute polar positions)
luma[h][s] = additive luma adjustment (optional, defaults to zeros)
Replicates the behavior of the native algClutLib Hsv2Clut_array function.
"""
if luma is None:
luma = init_luma_grid()
grid_25 = grid + [grid[0]]
luma_25 = luma + [luma[0]]
hue_lut = [[[0.0] * (HUE_SECTORS + 1) for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
sat_lut = [[[0.0] * (HUE_SECTORS + 1) for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
luma_lut = [[[0.0] * (HUE_SECTORS + 1) for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
for l in range(LUMA_LEVELS):
for s in range(SAT_COLUMNS):
for h in range(HUE_SECTORS + 1):
theta, r_norm = grid_25[h][s]
if h == HUE_SECTORS:
hue_lut[l][s][h] = 360.0
luma_lut[l][s][h] = luma_25[0][s]
elif s > 0:
hue_lut[l][s][h] = theta
luma_lut[l][s][h] = luma_25[h][s]
else:
hue_lut[l][s][h] = h * INTERVAL_THETA
luma_lut[l][s][h] = luma_25[h][s]
sat_lut[l][s][h] = r_norm
rgb_deltas = [[[[0.0] * GRID_DIM for _ in range(GRID_DIM)] for _ in range(GRID_DIM)] for _ in range(3)]
for ri in range(GRID_DIM):
for gi in range(GRID_DIM):
for bi in range(GRID_DIM):
r = ri / 16.0
g = gi / 16.0
b = bi / 16.0
h, s, v = colorsys.rgb_to_hsv(r, g, b)
new_hue, new_r, l_adj = _lookup_absolute(h, s, v, hue_lut, sat_lut, luma_lut)
new_h = (new_hue / 360.0) % 1.0
new_s = max(0.0, min(1.0, new_r / FULL_R_VALUE))
new_v = max(0.0, min(1.0, v + l_adj))
r_new, g_new, b_new = colorsys.hsv_to_rgb(new_h, new_s, new_v)
rgb_deltas[0][ri][gi][bi] = r_new - r
rgb_deltas[1][ri][gi][bi] = g_new - g
rgb_deltas[2][ri][gi][bi] = b_new - b
return pack_clut(rgb_deltas)
def _lookup_absolute(
h: float, s: float, v: float,
hue_lut: List[List[List[float]]],
sat_lut: List[List[List[float]]],
luma_lut: List[List[List[float]]],
) -> Tuple[float, float, float]:
"""Trilinearly interpolate absolute-position HSV grids.
Uses sat_col = s * (SAT_COLUMNS-1) mapping (not divided by FULL_R_VALUE)
since the grid stores absolute r_norm values in [0, FULL_R_VALUE].
"""
hue_pos = h * HUE_SECTORS
sat_pos = s * (SAT_COLUMNS - 1)
luma_pos = v * (LUMA_LEVELS - 1)
h_idx = min(int(hue_pos), HUE_SECTORS - 1)
h_frac = hue_pos - h_idx
h_next = h_idx + 1
s_idx = min(int(sat_pos), SAT_COLUMNS - 2)
s_frac = max(0.0, min(1.0, sat_pos - s_idx))
l_idx = min(int(luma_pos), LUMA_LEVELS - 2)
l_frac = max(0.0, min(1.0, luma_pos - l_idx))
hue_val = _trilinear(hue_lut, l_idx, s_idx, h_idx, h_next, l_frac, s_frac, h_frac)
sat_val = _trilinear(sat_lut, l_idx, s_idx, h_idx, h_next, l_frac, s_frac, h_frac)
luma_val = _trilinear(luma_lut, l_idx, s_idx, h_idx, h_next, l_frac, s_frac, h_frac)
return hue_val, sat_val, luma_val
+67
View File
@@ -0,0 +1,67 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""RGB to correlated color temperature conversion via McCamy's approximation."""
# sRGB to CIE XYZ (D65 illuminant) matrix
_SRGB_TO_XYZ = [
[0.4124564, 0.3575761, 0.1804375],
[0.2126729, 0.7151522, 0.0721750],
[0.0193339, 0.1191920, 0.9503041],
]
def _linearize(c: int) -> float:
"""Inverse sRGB companding for an 8-bit component."""
s = c / 255.0
if s <= 0.04045:
return s / 12.92
return ((s + 0.055) / 1.055) ** 2.4
def rgb_to_cct(r: int, g: int, b: int) -> int:
"""Convert an sRGB color to correlated color temperature in Kelvin.
Uses sRGB linearization, then CIE XYZ conversion, then McCamy's
cubic approximation from xy chromaticity coordinates.
Result is clamped to the camera's 2000-10000 K range.
"""
lr, lg, lb = _linearize(r), _linearize(g), _linearize(b)
X = _SRGB_TO_XYZ[0][0] * lr + _SRGB_TO_XYZ[0][1] * lg + _SRGB_TO_XYZ[0][2] * lb
Y = _SRGB_TO_XYZ[1][0] * lr + _SRGB_TO_XYZ[1][1] * lg + _SRGB_TO_XYZ[1][2] * lb
Z = _SRGB_TO_XYZ[2][0] * lr + _SRGB_TO_XYZ[2][1] * lg + _SRGB_TO_XYZ[2][2] * lb
total = X + Y + Z
if total < 1e-10:
return 6500
x = X / total
y = Y / total
# Guard against degenerate chromaticity near the singularity
denom = 0.1858 - y
if abs(denom) < 1e-10:
return 6500
n = (x - 0.3320) / denom
cct = 449.0 * n**3 + 3525.0 * n**2 + 6823.3 * n + 5520.33
return max(2000, min(10000, int(round(cct))))
+454
View File
@@ -0,0 +1,454 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Parameter definitions and value conversion tables for the YoloCam S3."""
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from . import yolocam_pb2 as pb
# S3 ISO values (sent as actual values, not indices)
ISO_VALUES: List[int] = [
100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250,
1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 9600, 12800,
]
# Shutter speed denominator -> microseconds (protocol uses microseconds)
SHUTTER_TABLE: Dict[int, int] = {
8000: 125, 6400: 156, 5000: 200, 4000: 250,
3200: 312, 2500: 400, 2000: 500, 1600: 625,
1250: 800, 1000: 1000, 800: 1250, 640: 1562,
500: 2000, 400: 2500, 320: 3125, 250: 4000,
200: 5000, 160: 6250, 125: 8000, 100: 10000,
80: 12500, 60: 16666, 50: 20000, 30: 33333,
25: 40000,
}
SHUTTER_REVERSE: Dict[int, int] = {v: k for k, v in SHUTTER_TABLE.items()}
# Aperture index -> f-stop label
APERTURE_TABLE: Dict[int, str] = {
0: "F1.0", 1: "F1.1", 2: "F1.3", 3: "F1.4",
4: "F1.6", 5: "F1.7", 6: "F1.8", 7: "F2.0",
8: "F2.2", 9: "F2.5", 10: "F2.8", 11: "F3.2",
12: "F3.6", 13: "F4.0", 14: "F4.5", 15: "F5.0",
16: "F5.7", 17: "F6.3", 18: "F7.1", 19: "F8.0",
20: "F9.0", 21: "F10.1", 22: "F11.3", 23: "F12.7",
24: "F14.3", 25: "F16.0", 26: "F18.0", 27: "F20.2",
28: "F22.6", 29: "F25.4", 30: "F28.5", 31: "F32.0",
}
# Zoom raw value <-> multiplier conversion
ZOOM_RAW_MIN = 50
ZOOM_RAW_MAX = 98
ZOOM_MULT_MIN = 1.0
ZOOM_MULT_MAX = 4.0
def zoom_raw_to_mult(raw: int) -> float:
"""Convert raw zoom value (50-98) to multiplier (1.0x-4.0x)."""
return 0.0625 * raw - 2.125
def zoom_mult_to_raw(mult: float) -> int:
"""Convert zoom multiplier (1.0x-4.0x) to raw value (50-98)."""
return round((mult + 2.125) / 0.0625)
def sharpness_to_wire(value: int) -> int:
"""Convert display sharpness (-10 to 30) to wire format.
Values -1 to -10 are sent as 61 to 70 respectively. Values 0-30 are sent as-is.
"""
if value < 0:
return 60 - value
return value
def sharpness_from_wire(raw: int) -> int:
"""Convert wire format to display sharpness (-10 to 30).
Raw 61-70 maps back to -1 to -10 respectively. Values 0-30 are returned as-is.
"""
if 61 <= raw <= 70:
return 60 - raw
return raw
def format_shutter(us: int) -> str:
"""Format shutter microseconds as a fraction string (e.g. '1/1000s')."""
if us in SHUTTER_REVERSE:
return f"1/{SHUTTER_REVERSE[us]}s"
return f"{us}us"
def format_aperture(index: int) -> str:
"""Format aperture index as f-stop string."""
return APERTURE_TABLE.get(index, f"idx:{index}")
def format_zoom(raw: int) -> str:
"""Format raw zoom value as multiplier string."""
return f"{zoom_raw_to_mult(raw):.1f}x"
def find_nearest_aperture(f_stop: float) -> int:
"""Find the aperture index closest to the given f-stop value."""
best_idx = 0
best_diff = float('inf')
for idx, label in APERTURE_TABLE.items():
f_val = float(label[1:])
if abs(f_val - f_stop) < best_diff:
best_diff = abs(f_val - f_stop)
best_idx = idx
return best_idx
@dataclass
class ParamDef:
name: str
cid: int
description: str
control_type: str
min_val: Optional[int] = None
max_val: Optional[int] = None
default: Optional[int] = None
value_map: Optional[Dict[int, str]] = field(default=None)
category: str = ""
# Control types:
# "slider" - continuous numeric range
# "toggle" - 0/1 on/off
# "segment" - small set of discrete choices (2-5 options)
# "dropdown" - larger set of choices
# "readonly" - read-only info
# "zoom" - zoom multiplier (special conversion)
# "setonly" - write-only, no read
PARAMS: Dict[str, ParamDef] = {
# Image quality
"brightness": ParamDef(
"brightness", pb.CID_BRIGHTNESS, "Image brightness",
"slider", 0, 100, 50, category="Image Quality",
),
"sharpness": ParamDef(
"sharpness", pb.CID_SHARPNESS, "Image sharpness",
"slider", -10, 30, 5, category="Image Quality",
),
"contrast": ParamDef(
"contrast", pb.CID_CONTRAST, "Image contrast",
"slider", 0, 100, 50, category="Image Quality",
),
"saturation": ParamDef(
"saturation", pb.CID_SATURATION, "Image saturation",
"slider", 0, 100, 50, category="Image Quality",
),
"hue": ParamDef(
"hue", pb.CID_HUE, "Image hue",
"slider", 0, 100, 50, category="Image Quality",
),
"gamma": ParamDef(
"gamma", pb.CID_GAMMA, "Image gamma",
"slider", 0, 100, 50, category="Image Quality",
),
# Zoom
"zoom": ParamDef(
"zoom", pb.CID_ZOOM, "Digital zoom",
"zoom", ZOOM_RAW_MIN, ZOOM_RAW_MAX, ZOOM_RAW_MIN, category="Zoom",
),
"zoom-speed": ParamDef(
"zoom-speed", pb.CID_ZOOM_SPEED, "Zoom speed",
"setonly", 1, 5, 3, category="Zoom",
),
# Exposure
"exposure-mode": ParamDef(
"exposure-mode", pb.CID_EXPOSURE_MODE, "Exposure mode",
"segment", 0, 1, 0, {0: "Auto", 1: "Manual"}, category="Exposure",
),
"exposure-ev": ParamDef(
"exposure-ev", pb.CID_EXPOSURE_EV, "EV compensation (8=0EV)",
"slider", 0, 16, 8, category="Exposure",
),
"exposure-iso": ParamDef(
"exposure-iso", pb.CID_EXPOSURE_ISO, "ISO",
"dropdown", 100, 12800, 400,
{v: str(v) for v in ISO_VALUES},
category="Exposure",
),
"exposure-time": ParamDef(
"exposure-time", pb.CID_EXPOSURE_TIME, "Shutter speed",
"dropdown", 125, 40000, 16666,
{us: f"1/{denom}" for denom, us in SHUTTER_TABLE.items()},
category="Exposure",
),
"exposure-aperture": ParamDef(
"exposure-aperture", pb.CID_EXPOSURE_APERTURE, "Aperture",
"dropdown", 0, 31, 10, APERTURE_TABLE, category="Exposure",
),
"exposure-lock": ParamDef(
"exposure-lock", pb.CID_EXPOSURE_LOCK, "Lock exposure",
"toggle", 0, 1, 0, category="Exposure",
),
"anti-flicker": ParamDef(
"anti-flicker", pb.CID_ANTI_FLICKER, "Anti-flicker",
"segment", 0, 2, 0, {0: "Off", 1: "50Hz", 2: "60Hz"}, category="Exposure",
),
"dynamic-range": ParamDef(
"dynamic-range", pb.CID_DYNAMIC_RANGE, "Dynamic range",
"slider", 0, 100, 50, category="Exposure",
),
"hdr": ParamDef(
"hdr", pb.CID_ENABLE_HDR, "HDR",
"toggle", 0, 1, 0, category="Exposure",
),
# White balance
"wb-mode": ParamDef(
"wb-mode", pb.CID_WHITE_BALANCE_MODE, "WB mode",
"segment", 0, 1, 1, {0: "Manual", 1: "Auto"}, category="White Balance",
),
"wb-temp": ParamDef(
"wb-temp", pb.CID_WHITE_BALANCE_TEMPERATURE, "Color temperature",
"slider", 2000, 10000, 5500, category="White Balance",
),
"wb-temp-shift": ParamDef(
"wb-temp-shift", pb.CID_WHITE_BALANCE_TEMPERATURE_SHIFT, "WB temp shift",
"slider", 0, 128, 64, category="White Balance",
),
"wb-lock": ParamDef(
"wb-lock", pb.CID_WHITE_BALANCE_LOCK, "Lock WB",
"toggle", 0, 1, 0, category="White Balance",
),
# Focus
"focus-mode": ParamDef(
"focus-mode", pb.CID_FOCUS_MODE, "Focus mode",
"segment", 1, 4, 1, {1: "AFS", 2: "Manual", 3: "AFC", 4: "Face"},
category="Focus",
),
"focus-level": ParamDef(
"focus-level", pb.CID_FOCUS_RECT_LEVEL, "Focus area size",
"segment", 0, 2, 0, {0: "Large", 1: "Medium", 2: "Small"},
category="Focus",
),
"focus-caf": ParamDef(
"focus-caf", pb.CID_ENABLE_CAF, "Continuous AF",
"toggle", 0, 1, 0, category="Focus",
),
"focus-trigger": ParamDef(
"focus-trigger", pb.CID_TRIGGER_SPEED, "AF trigger speed",
"slider", category="Focus",
),
"focus-manual": ParamDef(
"focus-manual", pb.CID_MANU_FOCUS_CODE, "Manual focus step",
"setonly", category="Focus",
),
"face-roi": ParamDef(
"face-roi", pb.CID_ENABLE_FACE_ROI, "Face-detect ROI",
"setonly", 0, 1, 0, category="Focus",
),
# Video format
"resolution": ParamDef(
"resolution", pb.CID_RESOLUTION, "Resolution setting",
"dropdown", category="Video",
),
"frame-rate": ParamDef(
"frame-rate", pb.CID_FRAME_RATE, "Frame rate",
"dropdown", value_map={25: "25", 30: "30", 50: "50", 60: "60"},
category="Video",
),
"scene": ParamDef(
"scene", pb.CID_SCENE, "Scene preset",
"setonly", category="Video",
),
# Lens correction
"distortion": ParamDef(
"distortion", pb.CID_ENABLE_DISTORTION, "Distortion correction",
"toggle", 0, 1, 0, category="Lens Correction",
),
"shading": ParamDef(
"shading", pb.CID_ENABLE_SHADING, "Shading correction",
"toggle", 0, 1, 0, category="Lens Correction",
),
# HDMI
"hdmi-format": ParamDef(
"hdmi-format", pb.CID_HDMI_OUTPUT_FORMAT, "HDMI output format",
"dropdown", 0, 3, 0, {0: "Auto", 1: "4K", 2: "1080p", 3: "720p"},
category="HDMI",
),
"hdmi-color": ParamDef(
"hdmi-color", pb.CID_HDMI_COLOR_SPACE, "HDMI color space",
"dropdown", 0, 2, 0, {0: "Auto", 1: "RGB", 2: "YUV422"},
category="HDMI",
),
# Tuning / color
"tuning": ParamDef(
"tuning", pb.CID_TUNING, "Image tuning parameters",
"setonly", category="Color / Tuning",
),
"clut": ParamDef(
"clut", pb.CID_ENABLE_CLUT, "Color LUT enable",
"toggle", 0, 1, 0, category="Color / Tuning",
),
"clut-attr": ParamDef(
"clut-attr", pb.CID_CLUT_ATTR, "Color LUT intensity",
"slider", 0, 255, 0, category="Color / Tuning",
),
# Audio
"au-volume": ParamDef(
"au-volume", pb.CID_AU_VOLUME, "Audio volume",
"slider", 0, 100, 50, category="Audio",
),
"au-denoise": ParamDef(
"au-denoise", pb.CID_AU_DENOISE, "Noise reduction",
"dropdown", 0, 3, 2, {0: "Close", 1: "Weak", 2: "Middle", 3: "Strong"},
category="Audio",
),
"au-gain": ParamDef(
"au-gain", pb.CID_AU_AUTO_GAIN, "Auto gain",
"toggle", 0, 1, 0, category="Audio",
),
"au-mic-type": ParamDef(
"au-mic-type", pb.CID_AU_MIC_TYPE, "Mic type",
"setonly", 0, 1, 0, {0: "Line", 1: "Mic"}, category="Audio",
),
"au-reverb": ParamDef(
"au-reverb", pb.CID_AU_REVERB, "Reverb level",
"dropdown", 0, 3, 0, {0: "Close", 1: "Weak", 2: "Middle", 3: "Strong"},
category="Audio",
),
"au-delay": ParamDef(
"au-delay", pb.CID_AU_DELAY, "Audio delay (ms)",
"slider", 0, 400, 0, category="Audio",
),
# Indicator LED
"indicator": ParamDef(
"indicator", pb.CID_INDICATOR_CTL, "Indicator LED control",
"setonly", category="LED / Indicator",
),
# AI tracking
"ai-tracking": ParamDef(
"ai-tracking", pb.CID_AI_TRACKING_CTRL, "AI tracking mode",
"segment", 0, 2, 2, {0: "Portrait", 1: "Thing", 2: "Off"},
category="AI Features",
),
# Streaming
"stream-cfg": ParamDef(
"stream-cfg", pb.CID_STREAM_CFG, "Stream configuration",
"setonly", category="Streaming",
),
"uvc": ParamDef(
"uvc", pb.CID_ENABLE_UVC, "UVC output enable",
"setonly", 0, 1, 0, category="Streaming",
),
# Device info (read-only)
"version": ParamDef(
"version", pb.CID_VERSION_INFO, "Camera firmware version info",
"readonly", category="Device Info",
),
"usb-version": ParamDef(
"usb-version", pb.CID_USB_VERSION, "USB protocol version",
"readonly", category="Device Info",
),
"lens-status": ParamDef(
"lens-status", pb.CID_LENS_STATUS, "Lens connection status",
"readonly", category="Device Info",
),
"lens-detail": ParamDef(
"lens-detail", pb.CID_GET_LENS_DETAIL, "Lens detail info",
"readonly", category="Device Info",
),
"lens-version": ParamDef(
"lens-version", pb.CID_LENS_VERSION, "Lens firmware version",
"readonly", category="Device Info",
),
"video-status": ParamDef(
"video-status", pb.CID_VIDEO_STATUS_CHANGED, "Video pipeline status",
"readonly", category="Device Info",
),
"au-version": ParamDef(
"au-version", pb.CID_AU_VERSION, "Audio module version",
"readonly", category="Device Info",
),
"disk-info": ParamDef(
"disk-info", pb.CID_DISK_INFO, "SD card info",
"readonly", category="Device Info",
),
"lowpower": ParamDef(
"lowpower", pb.CID_LOWPOWER_STATUS, "Low power status",
"readonly", category="Device Info",
),
"aperture-range": ParamDef(
"aperture-range", pb.CID_RANGE_OF_APERTURE, "Aperture range for lens",
"readonly", category="Device Info",
),
"exp-time-range": ParamDef(
"exp-time-range", pb.CID_RANGE_OF_EXP_TIME, "Exposure time range",
"readonly", category="Device Info",
),
}
# Grouped by category for UI panel layout
PARAM_CATEGORIES: Dict[str, List[str]] = {}
for _name, _pdef in PARAMS.items():
PARAM_CATEGORIES.setdefault(_pdef.category, []).append(_name)
def is_readable(param: ParamDef) -> bool:
return param.control_type not in ("setonly",)
def is_writable(param: ParamDef) -> bool:
return param.control_type not in ("readonly",)
def format_value(name: str, raw_value: int) -> str:
"""Format a raw protocol value into a human-readable display string."""
pdef = PARAMS.get(name)
if pdef is None:
return str(raw_value)
if name == "zoom":
return format_zoom(raw_value)
if name == "exposure-time":
return format_shutter(raw_value)
if name == "exposure-aperture":
return format_aperture(raw_value)
if pdef.value_map and raw_value in pdef.value_map:
return pdef.value_map[raw_value]
return str(raw_value)
+106
View File
@@ -0,0 +1,106 @@
# Copyright (C) 2026 Seth Hillbrand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Wire format for the YoloCam S3 SocketPacketPolicy dual-envelope protocol.
Outer (8 bytes): [0x08] [client_type] [0x00] [0x00] [LE32 inner_size]
Inner (6 bytes): [0xA5] [BE32 proto_size] [XOR header_checksum]
Payload (N bytes): serialized protobuf
Trailer (2 bytes): [XOR data_checksum] [0x5A]
"""
import struct
from typing import Union
OUTER_START_FLAG = 0x08
CLIENT_TYPE = 0x01
INNER_START_FLAG = 0xA5
INNER_END_FLAG = 0x5A
OUTER_HEADER_LEN = 8
CAMERA_IP = "192.168.126.10"
CAMERA_PORT = 12345
DEFAULT_TIMEOUT = 5.0
REQUEST_TIMEOUT_MS = 3000
MIN_REQUEST_INTERVAL = 0.1
HEARTBEAT_INTERVAL = 30.0
RECONNECT_THRESHOLD = 2
def xor_checksum(data: Union[bytes, bytearray]) -> int:
result = 0
for b in data:
result ^= b
return result
def pack_frame(payload: bytes) -> bytes:
"""Pack a serialized protobuf into the SocketPacketPolicy dual-envelope wire format."""
proto_size = len(payload)
inner_size = proto_size + 8
outer = bytes([OUTER_START_FLAG, CLIENT_TYPE, 0x00, 0x00]) + struct.pack('<I', inner_size)
inner_header = bytes([INNER_START_FLAG]) + struct.pack('>I', proto_size)
header_checksum = xor_checksum(inner_header)
data_checksum = xor_checksum(payload)
return outer + inner_header + bytes([header_checksum]) + payload + bytes([data_checksum, INNER_END_FLAG])
def unpack_frame(data: Union[bytes, bytearray]) -> bytes:
"""Unpack a complete dual-envelope frame, returning the protobuf payload.
Validates outer header, inner header checksum, data checksum, and end flag.
"""
if len(data) < OUTER_HEADER_LEN + 8:
raise ValueError(f"Frame too short: {len(data)} bytes")
if data[0] != OUTER_START_FLAG:
raise ValueError(f"Invalid outer start flag: 0x{data[0]:02x}")
inner_size = struct.unpack_from('<I', data, 4)[0]
if len(data) < OUTER_HEADER_LEN + inner_size:
raise ValueError(f"Incomplete frame: have {len(data)}, need {OUTER_HEADER_LEN + inner_size}")
inner = data[OUTER_HEADER_LEN:]
if inner[0] != INNER_START_FLAG:
raise ValueError(f"Invalid inner start flag: 0x{inner[0]:02x}")
proto_size = struct.unpack_from('>I', inner, 1)[0]
expected_hdr_xor = xor_checksum(inner[0:5])
if inner[5] != expected_hdr_xor:
raise ValueError(f"Header checksum mismatch: got 0x{inner[5]:02x}, expected 0x{expected_hdr_xor:02x}")
payload = inner[6:6 + proto_size]
expected_data_xor = xor_checksum(payload)
if inner[6 + proto_size] != expected_data_xor:
raise ValueError(
f"Data checksum mismatch: got 0x{inner[6 + proto_size]:02x}, expected 0x{expected_data_xor:02x}"
)
if inner[6 + proto_size + 1] != INNER_END_FLAG:
raise ValueError(f"Invalid end flag: 0x{inner[6 + proto_size + 1]:02x}")
return bytes(payload)
+530
View File
@@ -0,0 +1,530 @@
syntax = "proto3";
package tv.yunxi.protobuf;
enum MessageType {
TYPE_NONE = 0;
TYPE_REQUEST = 1;
TYPE_SET = 2;
TYPE_POST = 3;
TYPE_RESPONSE = 4;
TYPE_NOTIFY = 5;
}
enum CommandId {
CID_NONE = 0;
CID_VERSION_INFO = 1;
CID_UPDATE_ROM = 2;
CID_TRANSFORM_FILE = 3;
CID_SCENE = 4;
CID_FRAME_RATE = 5;
CID_RESOLUTION = 6;
CID_BRIGHTNESS = 7;
CID_SHARPNESS = 8;
CID_CONTRAST = 9;
CID_SATURATION = 10;
CID_HUE = 11;
CID_GAMMA = 12;
CID_ZOOM = 13;
CID_EXPOSURE_MODE = 14;
CID_EXPOSURE_EV = 15;
CID_ANTI_FLICKER = 16;
CID_EXPOSURE_ISO = 17;
CID_EXPOSURE_TIME = 18;
CID_EXPOSURE_ABSOLUTE_TIME = 19;
CID_EXPOSURE_APERTURE = 20;
CID_WHITE_BALANCE_MODE = 21;
CID_WHITE_BALANCE_TEMPERATURE = 22;
CID_FOCUS_MODE = 23;
CID_FOCUS_TARGET_LOCATION = 24;
CID_FOCUS_TARGET_DISTANCE = 25;
CID_ENABLE_DISTORTION = 26;
CID_ENABLE_SHADING = 27;
CID_EVENT_UPGRADE = 28;
CID_APP_ENV_MODE = 29;
CID_LENS_EVENT = 30;
CID_RANGE_OF_APERTURE = 31;
CID_RANGE_OF_EXP_TIME = 32;
CID_WHITE_BALANCE_OFFSET = 33;
CID_FOCUS_AREA_EVENT = 34;
CID_ERR_OCCURRED_EVENT = 35;
CID_DUMP_LOG = 36;
CID_LOG_PACKET = 37;
CID_FOCUS_RECT_LEVEL = 38;
CID_FOCUS_TARGET_LOCATION_S = 39;
CID_ACTUAL_EXP_ISO = 40;
CID_ACTUAL_EXP_TIME = 41;
CID_ENABLE_CAF = 42;
CID_ENABLE_DEBUG_MAIN_LAYER = 43;
CID_ENABLE_DEBUG_DEPTH_LAYER = 44;
CID_ENABLE_DEBUG_TARGET_LAYER = 45;
CID_SELECT_DEPTH_AREA = 46;
CID_TRIGGER_SPEED = 47;
CID_LENS_STATUS = 48;
CID_LENS_BASIC_INFO = 49;
CID_TUNING_FILE_INFO = 50;
CID_TUNING_FILE_EVENT = 51;
CID_TUNING_FILE_PKT = 52;
CID_TUNING = 53;
CID_SUPPORTED_TOF_CHANNELS = 54;
CID_TOF_CHANNEL_ID = 55;
CID_START_PROFILER = 56;
CID_TRANSPORT_PROFILER = 57;
CID_USB_TRANSFER_MODE = 58;
CID_FACE_BOUNDING_BOXES = 59;
CID_USB_VERSION = 60;
CID_HDMI_OUTPUT_FORMAT = 61;
CID_LENS_AMEND_CURVE = 62;
CID_GET_LENS_DETAIL = 63;
CID_LENS_RESET = 64;
CID_HDMI_COLOR_SPACE = 65;
CID_TERMINATED_BY_CAMERA = 66;
CID_BLE_SCAN_ON = 67;
CID_BLE_SCAN_OFF = 68;
CID_BLE_CONNECT = 69;
CID_BLE_DISCONNECT = 70;
CID_BLE_ADV_LIST = 71;
CID_BLE_ADV_CHANGED = 72;
CID_AU_VOLUME = 73;
CID_AU_VOLUME_BAR = 74;
CID_AU_DENOISE = 75;
CID_AU_REVERB = 76;
CID_AU_DELAY = 77;
CID_AU_AUTO_GAIN = 78;
CID_AU_MIC_TYPE = 79;
CID_AU_MIC_STATUS = 80;
CID_AU_MIC_EVENT = 81;
CID_LIGHT_STATUS_EVENT = 82;
CID_LIGHT_GET_STATUS = 83;
CID_LIGHT_CONNECT_EVENT = 84;
CID_LIGHT_SWITCH = 85;
CID_LIGHT_BRIGHTNESS = 86;
CID_LIGHT_COLOR_TEMP = 87;
CID_LENS_RESET_ONCE = 88;
CID_LIGHT_GET_CONNECTED_LIST = 89;
CID_AU_CODEC_GRADE = 90;
CID_INDICATOR_CTL = 91;
CID_DUMP_RAW = 92;
CID_DUMP_YUV = 93;
CID_ENABLE_CLUT = 94;
CID_CLUT_FILE = 95;
CID_CLUT_ATTR = 96;
CID_DUMP_PD_RAW = 97;
CID_ENABLE_HDR = 98;
CID_AI_TRACKING_CTRL = 99;
CID_DUMP_RAW_AE = 100;
CID_START_AI_PARAMS = 101;
CID_DYNAMIC_RANGE = 102;
CID_AU_VERSION = 103;
CID_WHITE_BALANCE_LOCK = 104;
CID_WHITE_BALANCE_TEMPERATURE_SHIFT = 105;
CID_EXPOSURE_LOCK = 106;
CID_BLE_OTA_FILE = 107;
CID_BLE_OTA_STATUS_EVENT = 108;
CID_BLE_GET_VERSION = 109;
CID_DUMP_RAW_YUV = 110;
CID_MANU_FOCUS_CODE = 111;
CID_ZOOM_SPEED = 112;
CID_LENS_VERSION = 113;
CID_STREAM_CFG = 202;
CID_STREAMING_START = 203;
CID_STREAMING_STOP = 204;
CID_RECORDING_START = 205;
CID_RECORDING_STOP = 206;
CID_STREAMING_STOPPED = 207;
CID_RECORDING_FINISHED = 208;
CID_DURATION_CHANGED = 209;
CID_VIDEO_STATUS_CHANGED = 210;
CID_ENABLE_UVC = 211;
CID_ENABLE_LOWPOWER_LED = 212;
CID_LOWPOWER_STATUS = 213;
CID_ENABLE_FACE_ROI = 214;
CID_STREAM_HEARTBEAT = 215;
CID_DISK_INFO = 301;
CID_DISK_FORMAT = 302;
CID_DISK_EVENT = 303;
CID_PTZ_RESET = 401;
CID_PTZ_POSITION = 402;
CID_PTZ_SPEED_LEVEL = 403;
CID_PTZ_DIRECTION = 404;
CID_PTZ_START_MOVING = 405;
CID_PTZ_STOP_MOVING = 406;
CID_PTZ_PRESET_POSITIONS = 407;
CID_PTZ_PRESET_POS = 408;
CID_CONFIGURE_WLAN = 501;
CID_WIFI_LIST = 502;
CID_RC_EVENT = 503;
CID_UNCONFIGURE_WLAN = 504;
CID_REMOTE_CTL_CONNECT_EVENT = 505;
CID_REMOTE_CTL_OTA_STATUS_EVENT = 506;
CID_REMOTE_CTL_GET_VERSION = 507;
CID_REMOTE_CTL_GET_STATUS = 508;
CID_REMOTE_CTL_OTA_FILE = 509;
DID_DRAW_LOG = 601;
}
message ManualExposureParams {
uint32 iso = 1;
uint32 shutter = 2;
uint32 aperture = 3;
}
message WhiteBalanceManual {
uint32 saturation = 1;
uint32 chroma = 2;
}
message WhiteBalanceOffset {
uint32 offset_r = 1;
uint32 offset_b = 2;
}
message Size {
uint32 width = 1;
uint32 height = 2;
}
message Range {
uint32 min = 1;
uint32 max = 2;
}
message RectF {
float left = 1;
float top = 2;
float right = 3;
float bottom = 4;
}
message Rect {
uint32 left = 1;
uint32 top = 2;
uint32 right = 3;
uint32 bottom = 4;
}
message FileInfo {
string file_path = 1;
string md5_info = 2;
string version = 3;
}
message VersionInfo {
string sys_version = 1;
string unique_id = 2;
string serial_num = 3;
string sys_code = 4;
}
message UpgradeEvent {
uint32 status = 1;
uint32 value = 2;
}
message TuningParam {
uint32 brightness = 1;
float curve = 2;
uint32 color_temp = 3;
}
message TuningFileInfo {
string description = 1;
string file_md5 = 2;
string scene_extra = 3;
string version = 4;
}
message TuningClutFile {
uint32 clut_size = 1;
repeated uint32 clut_data = 2;
string hsv_data = 3;
string extra = 4;
string updataflag = 5;
}
message TransportFile {
string file_path = 1;
string md5_info = 2;
}
message LensInfo {
string serial_number = 1;
}
message LensDetail {
uint32 lens_id = 1;
uint32 aperture = 2;
uint32 aperture_min = 3;
uint32 aperture_max = 4;
uint32 focal = 5;
uint32 detected = 6;
uint32 drive_times = 7;
uint32 drive_times_total = 8;
uint32 plug_times = 9;
uint32 plug_times_total = 10;
string serino = 11;
string hardware_version = 12;
uint32 origin_distance = 13;
uint32 amend_distance = 14;
}
message LensAmend {
uint32 lens_id = 1;
string serial = 2;
}
message LensReset {
uint32 lens_id = 1;
}
message StreamParam {
VEncParam venc_param = 1;
AEncParam aenc_param = 2;
}
message VEncParam {
uint32 codec = 1;
uint32 width = 2;
uint32 height = 3;
uint32 bitrate = 4;
uint32 rate = 5;
uint32 profile = 6;
}
message AEncParam {
uint32 codec = 1;
uint32 channels = 2;
uint32 sample_rate = 3;
uint32 bitrate = 4;
}
message StreamConfig {
OutputProtocol protocol = 1;
uint32 audio_enable = 2;
}
enum OutputProtocol {
OUTPUT_NONE = 0;
OUTPUT_RTMP = 1;
OUTPUT_RTSP = 2;
OUTPUT_SRT = 3;
}
message IndicatorCtl {
uint32 mode = 1;
uint32 brightness = 2;
}
message AiTrackingCtrl {
uint32 mode = 1;
}
message AiParams {
uint32 exp_iso = 1;
uint32 wb_r_gain = 2;
uint32 wb_b_gain = 3;
}
message ListInt {
repeated int32 values = 1;
}
message ListRectF {
repeated RectF values = 1;
}
message LensStatusEvent {
uint32 status = 1;
}
message LensVersionInfo {
string current_version = 1;
string latest_version = 2;
}
message PtzCtrl {
uint32 direction = 1;
uint32 speed = 2;
}
message PtzPosition {
float pitch = 1;
float yaw = 2;
}
message PtzSpeedLevel {
uint32 level = 1;
}
message PresetPos {
uint32 key = 1;
PtzPosition position = 2;
}
message PresetPositions {
repeated PresetPos entries = 1;
}
message DumpPdParam {
uint32 mode = 1;
}
message WlanConf {
string ssid = 1;
string psk = 2;
string key_mgmt = 3;
}
message WifiNetwork {
string ssid = 1;
string bssid = 2;
string flags = 3;
}
message WifiScanResults {
repeated WifiNetwork results = 1;
}
message BleScanParam {
uint32 cfg = 1;
int32 rssi = 2;
string name = 3;
}
message VideoStatus {
uint32 status = 1;
}
message DiskInfo {
uint32 total_size = 1;
uint32 available_size = 2;
uint32 fs_type = 3;
string smb_path = 4;
}
message RawImgInfo {
string file_path = 1;
}
message RCEvent {
uint32 rc_key = 1;
uint32 rc_key_status = 2;
}
message LightParam {
uint32 brightness = 1;
uint32 color_temp = 2;
string mac = 3;
}
message LightStatus {
uint32 status = 1;
string mac = 2;
}
message LightConnection {
string name = 1;
string mac = 2;
}
message LightConnectedList {
repeated LightConnection entries = 1;
}
message DrawRect {
uint32 left = 1;
uint32 top = 2;
uint32 right = 3;
uint32 bottom = 4;
uint32 color = 5;
}
message DrawText {
uint32 left = 1;
uint32 top = 2;
string context = 3;
uint32 color = 4;
}
message DrawInfo {
repeated DrawRect rects = 1;
repeated DrawText texts = 2;
}
message DrawInfoList {
repeated DrawInfo entries = 1;
}
message AdvInfo {
string name = 1;
string mac = 2;
int32 rssi = 3;
}
message AdvInfoList {
repeated AdvInfo entries = 1;
}
message StreamingOutput {
string url = 1;
string url_wlan = 2;
string file_fmt = 3;
}
message CommandBody {
oneof value {
uint32 int_val = 1;
string str_val = 2;
ManualExposureParams exposure_params = 3;
WhiteBalanceManual white_balance_manual = 4;
TransportFile transport_file = 5;
Size size = 6;
Range range = 7;
Rect rect = 8;
FileInfo file_info = 9;
VersionInfo version_info = 10;
UpgradeEvent upgrade_event = 11;
LensStatusEvent lens_event = 12;
WhiteBalanceOffset white_balance_offset = 13;
RectF rect_f = 14;
LensInfo lens_info = 15;
TuningFileInfo tuning_file_info = 16;
TuningParam tuning_param = 17;
ListInt list_int = 18;
ListRectF list_rect_f = 19;
LensDetail lens_detail = 20;
LensAmend lens_amend = 21;
LensReset lens_reset = 22;
BleScanParam ble_scan_param = 23;
AdvInfo adv_info = 24;
LightConnection light_connection = 25;
LightStatus light_status = 26;
LightParam light_param = 27;
LightConnectedList light_connected_list = 28;
IndicatorCtl indicator_ctl = 29;
RawImgInfo raw_img_info = 30;
TuningClutFile tuning_clut_file = 31;
WlanConf wlan_conf = 32;
StreamParam stream_param = 33;
DiskInfo disk_info = 34;
PtzCtrl ptz_ctrl = 35;
DumpPdParam dump_pd_param = 36;
RCEvent rc_event = 37;
WifiScanResults wifi_list = 38;
AiTrackingCtrl ai_tracking_ctrl = 39;
AiParams ai_params = 40;
VideoStatus video_status = 41;
DrawInfoList draw_info_list = 42;
AdvInfoList adv_list = 43;
LensVersionInfo lens_version_info = 44;
}
}
message Message {
MessageType type = 1;
uint32 seq = 2;
uint32 timeout = 3;
uint32 resp_code = 4;
CommandId id = 5;
CommandBody body = 6;
}
File diff suppressed because one or more lines are too long