Files
thebearsandClaude Opus 5.5 07da135257 Add the vendor firmware: stock flash dump, update file, both unpacked
vendor/ holds the camera's 16 MB NOR dump (backup-ssc377d-nor16m.bin), the
vendor update V3.6.1.3, and their unpacked trees, which the RE tools and
notes read. verify.py now defaults to vendor/flash_dump_ssc377d, and the
docs point at vendor/ instead of folders beside the checkout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EfVNki7giKruPunvux6dDA
2026-10-29 14:23:37 -04:00

185 KiB
Raw Permalink Blame History

MC-L18D port: the exact code

Every file written or changed for the AnjoyVision MC-L18D port, generated from the files on disk on 2026-10-29. Nothing below was retyped:

  • New files appear in full.
  • Edits to existing OpenIPC files appear as unified diffs against the upstream version.
  • Files that only wrap another file (the sensor-driver patch) show their header and say what they contain.

Nothing is committed. The repositories and branches:

Repository Branch Base
openipc/firmware mcl18d-port tag latest (7d213e9)
openipc/sensors gc5603-infinity6c f9cbec3
openipc/linux-infinity6c mcl18d sigmastar-infinity6c (d17f67f1f)
openipc/onvif_simple_server ptz-fixes 7c8672f

Paths in sections 1–5 are relative to openipc/firmware unless they name another repository. Section 6 paths are relative to openipc/.

The prose documents (MCL18D-PORT.md, AF-BOARD-PROTOCOL.md, LEARNING-GUIDE.md, TECH-SPEC.md, vendor/firmware_MCL18D_V3.6.1.3/gpio_map.md) are not repeated here.

Contents

File index

File Status Lines
br-ext-chip-sigmastar/configs/ssc377d_mcl18d_defconfig new 78
br-ext-chip-sigmastar/board/infinity6c/infinity6c-ssc027a-mcl18d.config new (copy, 1 line changed) 2958
general/package/Config.in modified +1/-0
.github/scripts/ci-matrix.py modified +4/-1
br-ext-chip-sigmastar/board/infinity6c/mcl18d/linux/0001-arm-dts-infinity6c-add-anjvision-mc-l18d.patch new 54
sensors: sigmastar/infinity6c/sensor_gc5603_mipi.c new 954
general/package/sigmastar-osdrv-sensors/0001-sigmastar-infinity6c-add-gc5603-driver.patch new (wraps the driver) 960
general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar modified +6/-0
general/package/sigmastar-osdrv-infinity6c/files/sensor/configs/gc5603.bin new (binary copy) 137904 bytes
general/package/anjvision-mcl18d/Config.in new 28
general/package/anjvision-mcl18d/anjvision-mcl18d.mk new 31
general/package/anjvision-mcl18d/files/customizer.sh new 46
general/package/anjvision-mcl18d/files/muxes.sh new 16
general/package/anjvision-mcl18d/files/S94mcl18d new 59
general/package/anjvision-mcl18d/files/mcl18d-io new 57
general/package/anjvision-mcl18d/files/onvif.conf new 70
general/package/anjvision-mcl18d/files/onvif-passwd new 27
general/package/anjvision-mcl18d/files/pelco-ptz.conf new 38
general/package/anjvision-mcl18d/files/mcl18d-af new 309
general/package/anjvision-mcl18d/src/pelco.h new 144
general/package/anjvision-mcl18d/src/pelco.c new 199
general/package/anjvision-mcl18d/src/main.c new 666
general/package/anjvision-mcl18d/src/Makefile new 39
general/package/anjvision-mcl18d/src/tests/pelco_test.c new 250
general/package/anjvision-mcl18d/src/tests/e2e_head.py new 75
general/package/anjvision-mcl18d/src/tests/pelco_e2e.py new 138
general/package/anjvision-mcl18d/src/tests/onvif_e2e.py new 161
general/package/anjvision-mcl18d/src/tests/af_sim.py new 149
general/package/onvif-simple-server/03-ptz-absolute-relative-zoom-fixes.patch new 116
gc5603-difftest/emu_ko.py new 201
gc5603-difftest/difftest.py new 192
af-board-re/plt.py new 50
af-board-re/od.py new 72
af-board-re/emu.py new 267
af-board-re/verify.py new 302
builder/Dockerfile new 9

1. Board registration (openipc/firmware, branch mcl18d-port)

br-ext-chip-sigmastar/configs/ssc377d_mcl18d_defconfig

new, 78 lines. The board's Buildroot configuration. It is ssc377d_lite_defconfig with the differences shown in the diff after it.

# AnjoyVision MC-L18D: SSC377D + GalaxyCore GC5603, 16 MB NOR.
# Build with: make BOARD=ssc377d_mcl18d

# Architecture
BR2_arm=y
BR2_cortex_a35=y
BR2_ARM_FPU_NEON_VFPV4=y
BR2_ARM_INSTRUCTIONS_THUMB2=y

# Toolchain
BR2_TOOLCHAIN_EXTERNAL=y
BR2_TOOLCHAIN_EXTERNAL_CUSTOM=y
BR2_TOOLCHAIN_EXTERNAL_DOWNLOAD=y
BR2_TOOLCHAIN_EXTERNAL_URL="https://github.com/openipc/firmware/releases/download/$(OPENIPC_TOOLCHAIN).tgz"
BR2_TOOLCHAIN_EXTERNAL_CUSTOM_PREFIX="arm-openipc-linux-musleabihf"
BR2_TOOLCHAIN_EXTERNAL_HEADERS_5_10=y
BR2_TOOLCHAIN_EXTERNAL_CUSTOM_MUSL=y
BR2_TOOLCHAIN_EXTERNAL_CXX=y

# Kernel
BR2_LINUX_KERNEL=y
BR2_LINUX_KERNEL_CUSTOM_TARBALL=y
BR2_LINUX_KERNEL_CUSTOM_TARBALL_LOCATION="https://github.com/openipc/linux/archive/$(OPENIPC_KERNEL).tar.gz"
BR2_LINUX_KERNEL_USE_CUSTOM_CONFIG=y
BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="$(EXTERNAL_VENDOR)/board/$(OPENIPC_SOC_FAMILY)/infinity6c-ssc027a-mcl18d.config"
BR2_LINUX_KERNEL_PATCH="$(EXTERNAL_VENDOR)/board/$(OPENIPC_SOC_FAMILY)/mcl18d/linux"
BR2_LINUX_KERNEL_UIMAGE=y
BR2_LINUX_KERNEL_XZ=y

# Filesystem
BR2_PACKAGE_BUSYBOX_CONFIG="$(BR2_EXTERNAL)/package/busybox/busybox.config"
BR2_PACKAGE_EXFATPROGS=y
BR2_PACKAGE_UBOOT_TOOLS=y
BR2_PACKAGE_ZLIB=y
# BR2_PACKAGE_IFUPDOWN_SCRIPTS is not set
# BR2_PACKAGE_WIREGUARD_LINUX_COMPAT is not set
BR2_PACKAGE_WIREGUARD_TOOLS=y
BR2_PACKAGE_WIRELESS_REGDB=y
BR2_PACKAGE_WIRELESS_TOOLS=y
BR2_PACKAGE_WPA_SUPPLICANT=y
BR2_PACKAGE_WPA_SUPPLICANT_CLI=y
BR2_PACKAGE_WPA_SUPPLICANT_PASSPHRASE=y
BR2_TARGET_ROOTFS_CPIO=y
BR2_TARGET_ROOTFS_SQUASHFS=y
BR2_TARGET_ROOTFS_SQUASHFS4_XZ=y

# OpenIPC
BR2_OPENIPC_SOC_VENDOR="sigmastar"
BR2_OPENIPC_SOC_MODEL="ssc377d"
BR2_OPENIPC_SOC_FAMILY="infinity6c"
BR2_OPENIPC_VARIANT="lite"
BR2_OPENIPC_FLASH_SIZE="16"
BR2_OPENIPC_SNS_MODEL="gc5603"

# Packages
BR2_PACKAGE_DROPBEAR_OPENIPC=y
BR2_PACKAGE_EXFAT_OPENIPC=y
BR2_PACKAGE_IPCTOOL=y
BR2_PACKAGE_LIBCURL_OPENIPC=y
BR2_PACKAGE_LIBCURL_OPENIPC_CURL=y
# BR2_PACKAGE_LIBCURL_OPENIPC_PROXY_SUPPORT is not set
# BR2_PACKAGE_LIBCURL_OPENIPC_COOKIES_SUPPORT is not set
# BR2_PACKAGE_LIBCURL_OPENIPC_EXTRA_PROTOCOLS_FEATURES is not set
BR2_PACKAGE_LIBEVENT_OPENIPC=y
BR2_PACKAGE_LIBOGG_OPENIPC=y
BR2_PACKAGE_MAJESTIC_FONTS=y
BR2_PACKAGE_MAJESTIC_WEBUI=y
BR2_PACKAGE_MAJESTIC=y
BR2_PACKAGE_CPU_MODELS=y
# BR2_PACKAGE_CPU_MODELS_PERSON is not set
BR2_PACKAGE_MBEDTLS_OPENIPC=y
BR2_PACKAGE_OPUS_OPENIPC=y
BR2_PACKAGE_OPUS_OPENIPC_FIXED_POINT=y
BR2_PACKAGE_SIGMASTAR_OSDRV_INFINITY6C=y
BR2_PACKAGE_ANJVISION_MCL18D=y
BR2_PACKAGE_ONVIF_SIMPLE_SERVER=y
BR2_PACKAGE_VTUND_OPENIPC=y
BR2_PACKAGE_YAML_CLI=y

The same file as a diff against the stock ssc377d_lite_defconfig it was copied from:

--- br-ext-chip-sigmastar/configs/ssc377d_lite_defconfig	2026-10-27 23:05:58.477476354 -0400
+++ br-ext-chip-sigmastar/configs/ssc377d_mcl18d_defconfig	2026-10-28 00:18:03.310954416 -0400
@@ -1,3 +1,6 @@
+# AnjoyVision MC-L18D: SSC377D + GalaxyCore GC5603, 16 MB NOR.
+# Build with: make BOARD=ssc377d_mcl18d
+
 # Architecture
 BR2_arm=y
 BR2_cortex_a35=y
@@ -19,7 +22,8 @@
 BR2_LINUX_KERNEL_CUSTOM_TARBALL=y
 BR2_LINUX_KERNEL_CUSTOM_TARBALL_LOCATION="https://github.com/openipc/linux/archive/$(OPENIPC_KERNEL).tar.gz"
 BR2_LINUX_KERNEL_USE_CUSTOM_CONFIG=y
-BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="$(EXTERNAL_VENDOR)/board/$(OPENIPC_SOC_FAMILY)/infinity6c-ssc027a.config"
+BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="$(EXTERNAL_VENDOR)/board/$(OPENIPC_SOC_FAMILY)/infinity6c-ssc027a-mcl18d.config"
+BR2_LINUX_KERNEL_PATCH="$(EXTERNAL_VENDOR)/board/$(OPENIPC_SOC_FAMILY)/mcl18d/linux"
 BR2_LINUX_KERNEL_UIMAGE=y
 BR2_LINUX_KERNEL_XZ=y
 
@@ -45,7 +49,8 @@
 BR2_OPENIPC_SOC_MODEL="ssc377d"
 BR2_OPENIPC_SOC_FAMILY="infinity6c"
 BR2_OPENIPC_VARIANT="lite"
-BR2_OPENIPC_FLASH_SIZE="8"
+BR2_OPENIPC_FLASH_SIZE="16"
+BR2_OPENIPC_SNS_MODEL="gc5603"
 
 # Packages
 BR2_PACKAGE_DROPBEAR_OPENIPC=y
@@ -67,5 +72,7 @@
 BR2_PACKAGE_OPUS_OPENIPC=y
 BR2_PACKAGE_OPUS_OPENIPC_FIXED_POINT=y
 BR2_PACKAGE_SIGMASTAR_OSDRV_INFINITY6C=y
+BR2_PACKAGE_ANJVISION_MCL18D=y
+BR2_PACKAGE_ONVIF_SIMPLE_SERVER=y
 BR2_PACKAGE_VTUND_OPENIPC=y
 BR2_PACKAGE_YAML_CLI=y

br-ext-chip-sigmastar/board/infinity6c/infinity6c-ssc027a-mcl18d.config

new, 2958 lines: a verbatim copy of the stock infinity6c-ssc027a.config with one line changed, so that the kernel builds the MC-L18D device tree. The whole difference:

--- br-ext-chip-sigmastar/board/infinity6c/infinity6c-ssc027a.config	2026-10-27 23:05:58.476705769 -0400
+++ br-ext-chip-sigmastar/board/infinity6c/infinity6c-ssc027a-mcl18d.config	2026-10-27 23:35:10.587233815 -0400
@@ -313,7 +313,7 @@
 #
 # Options
 #
-CONFIG_SS_DTB_NAME="infinity6c-ssc027a-s01a"
+CONFIG_SS_DTB_NAME="infinity6c-ssc027a-s01a-mcl18d"
 CONFIG_SS_BUILTIN_DTB=y
 CONFIG_MS_KERNEL_TYPE=""
 CONFIG_SSTAR_CHIP_NAME="infinity6c"

general/package/Config.in

modified, +1 / -0 lines. Makes the new package visible to Buildroot's menu.

diff --git a/general/package/Config.in b/general/package/Config.in
index 43e780fa..fa826e44 100644
--- a/general/package/Config.in
+++ b/general/package/Config.in
@@ -2,6 +2,7 @@ source "$BR2_EXTERNAL_GENERAL_PATH/package/adaptive-link/Config.in"
 source "$BR2_EXTERNAL_GENERAL_PATH/package/aic8800-openipc/Config.in"
 source "$BR2_EXTERNAL_GENERAL_PATH/package/allwinner-osdrv-v83x/Config.in"
 source "$BR2_EXTERNAL_GENERAL_PATH/package/allwinner-osdrv-v85x/Config.in"
+source "$BR2_EXTERNAL_GENERAL_PATH/package/anjvision-mcl18d/Config.in"
 source "$BR2_EXTERNAL_GENERAL_PATH/package/anyka-osdrv-ak3918av130/Config.in"
 source "$BR2_EXTERNAL_GENERAL_PATH/package/atbm-wifi/Config.in"
 source "$BR2_EXTERNAL_GENERAL_PATH/package/atbm60xx/Config.in"

.github/scripts/ci-matrix.py

modified, +4 / -1 lines. Registers the board and the package as deliberately not built by CI, with reasons, so ci-matrix.py --self-test passes.

diff --git a/.github/scripts/ci-matrix.py b/.github/scripts/ci-matrix.py
index 81f11f5b..e544fd1f 100644
--- a/.github/scripts/ci-matrix.py
+++ b/.github/scripts/ci-matrix.py
@@ -139,6 +139,9 @@ UNBUILT_BOARDS = {
     # bit-identical images under different names. These two were already
     # explained in prose beside ALL_BOARDS; now they are checked.
     "gk7205v210_lite": "alias of gk7205v200_lite",
+    # One retail module (AnjoyVision MC-L18D), kept as a local port; per the
+    # firmware-vs-builder split a single device belongs to OpenIPC/builder.
+    "ssc377d_mcl18d": "single retail device (AnjoyVision MC-L18D), local port",
     "xm550_lite": "alias of xm530_lite",
 
     # Variants outside the lite/ultimate/neo set the matrix is built around.
@@ -321,7 +324,7 @@ UNBUILT_FAMILIES = {
 # this list when that board joins ALL_BOARDS, which waits for those modules
 # to have run on an AV130 camera.
 NOT_BUILT = {
-    "adaptive-link", "aic8800-openipc", "allwinner-osdrv-v83x",
+    "adaptive-link", "anjvision-mcl18d", "aic8800-openipc", "allwinner-osdrv-v83x",
     "anyka-osdrv-ak3918av130", "atbm-wifi",
     "aura-httpd", "baresip-openipc", "comgt", "f2fs-tools-openipc", "faceter-agent",
     "faceter-detector", "fdk-aac-openipc", "ffmpeg-openipc", "gdbserver-lite",

2. Kernel device tree

br-ext-chip-sigmastar/board/infinity6c/mcl18d/linux/0001-arm-dts-infinity6c-add-anjvision-mc-l18d.patch

new, 54 lines. Applied to the OpenIPC kernel by BR2_LINUX_KERNEL_PATCH. It adds one file, arch/arm/boot/dts/infinity6c-ssc027a-s01a-mcl18d.dts, which is also on branch mcl18d of openipc/linux-infinity6c with identical content.

diff --git a/arch/arm/boot/dts/infinity6c-ssc027a-s01a-mcl18d.dts b/arch/arm/boot/dts/infinity6c-ssc027a-s01a-mcl18d.dts
new file mode 100644
index 000000000..1a7658dc7
--- /dev/null
+++ b/arch/arm/boot/dts/infinity6c-ssc027a-s01a-mcl18d.dts
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * AnjoyVision MC-L18D: SSC377D on the SSC027A-S01A reference layout, GalaxyCore
+ * GC5603 on MIPI (I2C1, 2 lanes).
+ *
+ * Differences from the reference board, taken from the device tree in the
+ * vendor firmware:
+ *  - PAD_PWM0 is PWM0 (white light) and PAD_SPI0_CZ is PWM4 (infrared light),
+ *    the two lamp outputs on the D5 lighting connector.
+ *  - PAD_PWM1 is the Ethernet activity LED (D1 pin 8), not I2C0.
+ *  - PAD_FUART_RX/TX are the 2-wire FUART (ttyS2) used by the zoom/PTZ board.
+ *  - The SD card slot runs at 20 MHz with the default pad drive.
+ * PAD_SPI0_CK/DI/DO, PAD_PM_IRIN, PAD_FUART_CTS, PAD_SR_IO00/01 and
+ * PAD_SAR_GPIO1 stay GPIOs; see the anjvision-mcl18d package for their use.
+ */
+
+#include "infinity6c-ssc027a-s01a.dts"
+
+/ {
+	soc {
+		padmux {
+			schematic =
+				<GPIO_NR        PINMUX_FOR_UNKNOWN_MODE    MDRV_PUSE_NA>,
+				<PAD_PWM0       PINMUX_FOR_PWM0_MODE_1     MDRV_PUSE_PWM0>,
+				<PAD_SPI0_CZ    PINMUX_FOR_PWM4_MODE_2     MDRV_PUSE_PWM4>,
+				<PAD_PWM1       PINMUX_FOR_LED1_MODE_2     MDRV_PUSE_ETH1_LED>,
+				<PAD_FUART_RX   PINMUX_FOR_FUART_2W_MODE_1 MDRV_PUSE_FUART_RX>,
+				<PAD_FUART_TX   PINMUX_FOR_FUART_2W_MODE_1 MDRV_PUSE_FUART_TX>,
+				<PAD_I2C1_SCL   PINMUX_FOR_I2C1_MODE_1     MDRV_PUSE_I2C1_SCL>,
+				<PAD_I2C1_SDA   PINMUX_FOR_I2C1_MODE_1     MDRV_PUSE_I2C1_SDA>,
+				<PAD_SD_D1      PINMUX_FOR_SD0_MODE_1      MDRV_PUSE_SDIO1_D1>,
+				<PAD_SD_D0      PINMUX_FOR_SD0_MODE_1      MDRV_PUSE_SDIO1_D0>,
+				<PAD_SD_CLK     PINMUX_FOR_SD0_MODE_1      MDRV_PUSE_SDIO1_CLK>,
+				<PAD_SD_CMD     PINMUX_FOR_SD0_MODE_1      MDRV_PUSE_SDIO1_CMD>,
+				<PAD_SD_D3      PINMUX_FOR_SD0_MODE_1      MDRV_PUSE_SDIO1_D3>,
+				<PAD_SD_D2      PINMUX_FOR_SD0_MODE_1      MDRV_PUSE_SDIO1_D2>,
+				<PAD_FUART_RTS  PINMUX_FOR_GPIO_MODE       MDRV_PUSE_SDIO1_PWR>,
+				<PAD_PM_SD_CDZ  PINMUX_FOR_SD0_CDZ_MODE_1  MDRV_PUSE_SDIO1_CDZ>;
+		};
+
+		sdmmc {
+			slot-max-clks = <20000000>, <20000000>, <20000000>;
+			slot-clk-driving = <0>, <0>, <0>;
+			slot-cmd-driving = <0>, <0>, <0>;
+			slot-data-driving = <0>, <0>, <0>;
+		};
+	};
+};

3. GC5603 sensor driver

sensors: sigmastar/infinity6c/sensor_gc5603_mipi.c

new, 954 lines. On branch gc5603-infinity6c of openipc/sensors. Reconstructed from the vendor's gc5603_MIPI_1125.ko; the register tables were generated from that binary.

/*
 * GalaxyCore GC5603 MIPI sensor driver for SigmaStar Infinity6C (SSC377/SSC378).
 *
 * 2960x1666 @ 30 fps, 10-bit RAW, 2-lane MIPI, 27 MHz MCLK, I2C 0x62 (8-bit).
 *
 * Reconstructed from the vendor module gc5603_MIPI_1125.ko shipped on the
 * AnjoyVision MC-L18D (SSC377D) board. Register tables, line timing, the gain
 * table and the vendor's temperature-dependent black-level handling are kept
 * as the vendor built them. Two things differ:
 *
 *  - Orientation. The vendor driver maps CUS_ORIT_M0F0 to 0x022c=0x03 and its
 *    application inverts mirror and flip for this board, so the picture comes
 *    out upright at the sensor's native readout (0x022c=0x00). Here M0F0 is the
 *    native readout and majestic's image.mirror / image.flip do what they say.
 *  - Private state (the temperature level and the gain table limit) lives in
 *    the per-sensor params instead of module globals.
 */

#ifdef __cplusplus
extern "C" {
#endif

#include <drv_sensor.h>
#include <drv_sensor_common.h>
#include <sensor_i2c_api.h>

#ifdef __cplusplus
}
#endif

SENSOR_DRV_ENTRY_IMPL_BEGIN_EX(gc5603);

#ifndef ARRAY_SIZE
#define ARRAY_SIZE CAM_OS_ARRAY_SIZE
#endif

#define SENSOR_CHANNEL_NUM (0)
#define SENSOR_CHANNEL_MODE_LINEAR CUS_SENSOR_CHANNEL_MODE_REALTIME_NORMAL

#define SENSOR_MIPI_LANE_NUM (lane_num)

#define SENSOR_ISP_TYPE ISP_EXT
#define SENSOR_IFBUS_TYPE CUS_SENIF_BUS_MIPI
#define SENSOR_MIPI_HSYNC_MODE PACKET_HEADER_EDGE1
#define SENSOR_DATAPREC CUS_DATAPRECISION_10
#define SENSOR_DATAMODE CUS_SEN_10TO12_9000
#define SENSOR_BAYERID CUS_BAYER_BG
#define SENSOR_RGBIRID CUS_RGBIR_NONE
#define SENSOR_ORIT CUS_ORIT_M0F0

#define SENSOR_MAX_GAIN (128 * 1024) /* 62x analog x 2x digital, capped at 128x */
#define SENSOR_MIN_GAIN (1 * 1024)

#define Preview_MCLK_SPEED CUS_CMU_CLK_27MHZ
#define Preview_line_period 19047 /* ns: HTS 0x04b0, VTS 1750 at 30 fps */
#define vts_30fps 1750
#define Preview_WIDTH 2960
#define Preview_HEIGHT 1666
#define Preview_MAX_FPS 30
#define Preview_MIN_FPS 5

#define SENSOR_I2C_ADDR 0x62
#define SENSOR_I2C_SPEED 320000
#define SENSOR_I2C_LEGACY I2C_NORMAL_MODE
#define SENSOR_I2C_FMT I2C_FMT_A16D8

#define SENSOR_PWDN_POL CUS_CLK_POL_POS
#define SENSOR_RST_POL CUS_CLK_POL_NEG
#define SENSOR_VSYNC_POL CUS_CLK_POL_NEG
#define SENSOR_HSYNC_POL CUS_CLK_POL_NEG
#define SENSOR_PCLK_POL CUS_CLK_POL_POS

/* Exposure must stay this many lines under the frame length. */
#define EXPO_VTS_MARGIN 8

#if defined(SENSOR_MODULE_VERSION)
#define TO_STR_NATIVE(e) #e
#define TO_STR_PROXY(m, e) m(e)
#define MACRO_TO_STRING(e) TO_STR_PROXY(TO_STR_NATIVE, e)
static char* sensor_module_version = MACRO_TO_STRING(SENSOR_MODULE_VERSION);
module_param(sensor_module_version, charp, S_IRUGO);
#endif

static int pCus_SetAEGain(ms_cus_sensor* handle, u32 gain);
static int pCus_SetAEUSecs(ms_cus_sensor* handle, u32 us);
static int pCus_SetFPS(ms_cus_sensor* handle, u32 fps);
static int pCus_AEStatusNotify(ms_cus_sensor* handle, CUS_CAMSENSOR_AE_STATUS_NOTIFY status);

typedef struct {
    struct {
        u32 vts;
        u32 final_gain;
        u32 fps;
        u32 line;
    } expo;
    CUS_CAMSENSOR_ORIT orit;
    bool dirty;
    bool orient_dirty;
    /* Vendor temperature handling: see gc5603_temp_comp(). */
    u8 temp_level;
    u8 temp_hot;
    u8 gain_idx_count;
    I2C_ARRAY tVts_reg[2];
    I2C_ARRAY tGain_reg[11];
    I2C_ARRAY tExpo_reg[2];
    I2C_ARRAY tMirror_reg[22];
    I2C_ARRAY tMirrorPost_reg[3];
} gc5603_params;

const static I2C_ARRAY Sensor_id_table[] = {
    { 0x03f0, 0x56 },
    { 0x03f1, 0x03 },
};

typedef struct {
    u32 gain;
    u16 r0614, r0615, r0225, r1467, r1468, r00b8, r00b9;
} Gain_ARRAY;

const static I2C_ARRAY Sensor_init_table[] = {
    { 0x03fe, 0xf0 },
    { 0x03fe, 0x00 },
    { 0x03fe, 0x10 },
    { 0x03fe, 0x00 },
    { 0x0a38, 0x02 },
    { 0x0a38, 0x03 },
    { 0x0a20, 0x07 },
    { 0x06ab, 0x03 },
    { 0x061b, 0x03 },
    { 0x061c, 0x50 },
    { 0x061d, 0x05 },
    { 0x061e, 0x70 },
    { 0x061f, 0x03 },
    { 0x0a21, 0x08 },
    { 0x0a34, 0x40 },
    { 0x0a35, 0x11 },
    { 0x0a36, 0x5e },
    { 0x0a37, 0x03 },
    { 0x0314, 0x50 },
    { 0x0315, 0x32 },
    { 0x031c, 0xce },
    { 0x0219, 0x47 },
    { 0x0342, 0x04 },
    { 0x0343, 0xb0 },
    { 0x0340, 0x06 },
    { 0x0341, 0xd6 },
    { 0x0345, 0x02 },
    { 0x0347, 0x02 },
    { 0x0348, 0x0b },
    { 0x0349, 0x98 },
    { 0x034a, 0x06 },
    { 0x034b, 0x8a },
    { 0x0094, 0x0b },
    { 0x0095, 0x90 },
    { 0x0096, 0x06 },
    { 0x0097, 0x82 },
    { 0x0099, 0x04 },
    { 0x009b, 0x04 },
    { 0x060c, 0x01 },
    { 0x060e, 0xd2 },
    { 0x060f, 0x05 },
    { 0x070c, 0x01 },
    { 0x070e, 0xd2 },
    { 0x070f, 0x05 },
    { 0x0909, 0x07 },
    { 0x0902, 0x04 },
    { 0x0904, 0x0b },
    { 0x0907, 0x54 },
    { 0x0908, 0x06 },
    { 0x0903, 0x9d },
    { 0x072a, 0x1c },
    { 0x072b, 0x1c },
    { 0x0724, 0x2b },
    { 0x0727, 0x2b },
    { 0x1466, 0x18 },
    { 0x1467, 0x08 },
    { 0x1468, 0x10 },
    { 0x1469, 0x80 },
    { 0x146a, 0xe8 },
    { 0x1412, 0x20 },
    { 0x0707, 0x07 },
    { 0x0737, 0x0f },
    { 0x0704, 0x01 },
    { 0x0706, 0x03 },
    { 0x0716, 0x03 },
    { 0x0708, 0xc8 },
    { 0x0718, 0xc8 },
    { 0x061a, 0x02 },
    { 0x1430, 0x80 },
    { 0x1407, 0x10 },
    { 0x1408, 0x16 },
    { 0x1409, 0x03 },
    { 0x1438, 0x01 },
    { 0x02ce, 0x03 },
    { 0x0245, 0xc9 },
    { 0x023a, 0x08 },
    { 0x02cd, 0x88 },
    { 0x0612, 0x02 },
    { 0x0613, 0xc7 },
    { 0x0243, 0x03 },
    { 0x0089, 0x03 },
    { 0x0002, 0xab },
    { 0x0040, 0xa3 },
    { 0x0075, 0x64 },
    { 0x0004, 0x0f },
    { 0x0053, 0x0a },
    { 0x0205, 0x0c },
    { 0x0052, 0x02 },
    { 0x0076, 0x01 },
    { 0x021a, 0x10 },
    { 0x0049, 0x0f },
    { 0x004a, 0x3c },
    { 0x004b, 0x00 },
    { 0x0430, 0x25 },
    { 0x0431, 0x25 },
    { 0x0432, 0x25 },
    { 0x0433, 0x25 },
    { 0x0434, 0x59 },
    { 0x0435, 0x59 },
    { 0x0436, 0x59 },
    { 0x0437, 0x59 },
    { 0x0a67, 0x80 },
    { 0x0a54, 0x0e },
    { 0x0a65, 0x10 },
    { 0x0a98, 0x04 },
    { 0x05be, 0x00 },
    { 0x05a9, 0x01 },
    { 0x0023, 0x00 },
    { 0x0022, 0x00 },
    { 0x0025, 0x00 },
    { 0x0024, 0x00 },
    { 0x0028, 0x0b },
    { 0x0029, 0x98 },
    { 0x002a, 0x06 },
    { 0x002b, 0x86 },
    { 0x0a83, 0xe0 },
    { 0x0a72, 0x02 },
    { 0x0a73, 0x60 },
    { 0x0a75, 0x41 },
    { 0x0a70, 0x03 },
    { 0x0a5a, 0x80 },
    { 0x0181, 0x30 },
    { 0x0182, 0x05 },
    { 0x0185, 0x01 },
    { 0x0180, 0x46 },
    { 0x0100, 0x08 },
    { 0x010d, 0x74 },
    { 0x010e, 0x0e },
    { 0x0113, 0x02 },
    { 0x0114, 0x01 },
    { 0x0115, 0x10 },
    { 0x0100, 0x09 },
    { 0xffff, 0x14 }, // delay 20 ms
    { 0x0a70, 0x00 },
    { 0x0080, 0x02 },
    { 0x0a67, 0x00 },
};

/* 0x031d selects the register page: 0x2d opens 0x0614/0x0615/0x0225, 0x28 closes it. */
const static I2C_ARRAY gain_reg[] = {
    { 0x031d, 0x2d },
    { 0x0614, 0x00 },
    { 0x0615, 0x00 },
    { 0x0225, 0x00 },
    { 0x031d, 0x28 },
    { 0x1467, 0x08 },
    { 0x1468, 0x19 },
    { 0x00b8, 0x01 },
    { 0x00b9, 0x00 },
    { 0x0064, 0x01 },
    { 0x0065, 0x00 },
};

const static I2C_ARRAY expo_reg[] = {
    { 0x0203, 0xce },
    { 0x0202, 0x06 },
};

const static I2C_ARRAY vts_reg[] = {
    { 0x0340, 0x06 },
    { 0x0341, 0xd6 },
};

/*
 * Written on an orientation change. Only 0x022c (bit0 mirror, bit1 flip),
 * 0x0063 (same bits) and 0x0a73 (0x60 | bits) vary; the rest re-runs the
 * readout start sequence the init table ends with.
 */
const static I2C_ARRAY mirror_reg[] = {
    { 0x022c, 0x00 },
    { 0x0063, 0x00 },
    { 0x0a67, 0x80 },
    { 0x0a54, 0x0e },
    { 0x0a65, 0x10 },
    { 0x0a98, 0x04 },
    { 0x05be, 0x00 },
    { 0x05a9, 0x01 },
    { 0x0022, 0x00 },
    { 0x0023, 0x00 },
    { 0x0024, 0x00 },
    { 0x0025, 0x00 },
    { 0x0028, 0x0b },
    { 0x0029, 0x98 },
    { 0x002a, 0x06 },
    { 0x002b, 0x86 },
    { 0x0a83, 0xe0 },
    { 0x0a72, 0x02 },
    { 0x0a73, 0x60 },
    { 0x0a75, 0x41 },
    { 0x0a70, 0x03 },
    { 0x0a5a, 0x80 },
};

const static I2C_ARRAY mirror_post_reg[] = {
    { 0x0a70, 0x00 },
    { 0x0080, 0x02 },
    { 0x0a67, 0x00 },
};

static const Gain_ARRAY gain_table[] = {
    /* gain(x1024), 0x0614, 0x0615, 0x0225, 0x1467, 0x1468, 0x00b8, 0x00b9 */
    {   1024, 0x00, 0x00, 0x04, 0x19, 0x19, 0x01, 0x00 },
    {   1184, 0x90, 0x02, 0x04, 0x1b, 0x1b, 0x01, 0x0a },
    {   1312, 0x00, 0x00, 0x00, 0x19, 0x19, 0x01, 0x12 },
    {   1536, 0x90, 0x02, 0x00, 0x1b, 0x1b, 0x01, 0x20 },
    {   1792, 0x01, 0x00, 0x00, 0x19, 0x19, 0x01, 0x30 },
    {   2128, 0x91, 0x02, 0x00, 0x1b, 0x1b, 0x02, 0x05 },
    {   2448, 0x02, 0x00, 0x00, 0x1a, 0x1a, 0x02, 0x19 },
    {   3056, 0x92, 0x02, 0x00, 0x1c, 0x1c, 0x02, 0x3f },
    {   3584, 0x03, 0x00, 0x00, 0x1a, 0x1a, 0x03, 0x20 },
    {   4256, 0x93, 0x02, 0x00, 0x1d, 0x1d, 0x04, 0x0a },
    {   5152, 0x00, 0x00, 0x01, 0x1d, 0x1d, 0x05, 0x02 },
    {   6032, 0x90, 0x02, 0x01, 0x20, 0x20, 0x05, 0x39 },
    {   7104, 0x01, 0x00, 0x01, 0x1e, 0x1e, 0x06, 0x3c },
    {   8400, 0x91, 0x02, 0x01, 0x20, 0x20, 0x08, 0x0d },
    {   9744, 0x02, 0x00, 0x01, 0x20, 0x20, 0x09, 0x21 },
    {  11504, 0x92, 0x02, 0x01, 0x22, 0x22, 0x0b, 0x0f },
    {  13680, 0x03, 0x00, 0x01, 0x21, 0x21, 0x0d, 0x17 },
    {  16176, 0x93, 0x02, 0x01, 0x23, 0x23, 0x0f, 0x33 },
    {  19200, 0x04, 0x00, 0x01, 0x23, 0x23, 0x12, 0x30 },
    {  22784, 0x94, 0x02, 0x01, 0x25, 0x25, 0x16, 0x10 },
    {  27024, 0x05, 0x00, 0x01, 0x24, 0x24, 0x1a, 0x19 },
    {  32048, 0x95, 0x02, 0x01, 0x26, 0x26, 0x1f, 0x13 },
    {  38016, 0x06, 0x00, 0x01, 0x26, 0x26, 0x25, 0x08 },
    {  45104, 0x96, 0x02, 0x01, 0x28, 0x28, 0x2c, 0x03 },
    {  53488, 0xb6, 0x04, 0x01, 0x28, 0x28, 0x34, 0x0f },
    {  63440, 0x86, 0x06, 0x01, 0x2a, 0x2a, 0x3d, 0x3d },
};

#define GAIN_TABLE_SIZE ARRAY_SIZE(gain_table)
#define GAIN_IDX_COUNT_MIN 17

#undef SENSOR_NAME
#define SENSOR_NAME gc5603

#define SensorReg_Read(_reg, _data) (handle->i2c_bus->i2c_rx(handle->i2c_bus, &(handle->i2c_cfg), _reg, _data))
#define SensorReg_Write(_reg, _data) (handle->i2c_bus->i2c_tx(handle->i2c_bus, &(handle->i2c_cfg), _reg, _data))
#define SensorRegArrayW(_reg, _len) (handle->i2c_bus->i2c_array_tx(handle->i2c_bus, &(handle->i2c_cfg), (_reg), (_len)))
#define SensorRegArrayR(_reg, _len) (handle->i2c_bus->i2c_array_rx(handle->i2c_bus, &(handle->i2c_cfg), (_reg), (_len)))

static int cus_camsensor_release_handle(ms_cus_sensor* handle);

static int pCus_poweron(ms_cus_sensor* handle, u32 idx)
{
    ISensorIfAPI* sensor_if = handle->sensor_if_api;

    sensor_if->SetIOPad(idx, handle->sif_bus, handle->interface_attr.attr_mipi.mipi_lane_num);
    sensor_if->SetCSI_Clk(idx, CUS_CSI_CLK_216M);
    sensor_if->SetCSI_Lane(idx, handle->interface_attr.attr_mipi.mipi_lane_num, 1);
    sensor_if->SetCSI_LongPacketType(idx, 0, 0x1C00, 0);

    sensor_if->PowerOff(idx, !handle->pwdn_POLARITY);
    SENSOR_USLEEP(1000);
    sensor_if->Reset(idx, handle->reset_POLARITY);
    SENSOR_USLEEP(1000);
    sensor_if->PowerOff(idx, handle->pwdn_POLARITY);
    SENSOR_USLEEP(1000);
    sensor_if->Reset(idx, !handle->reset_POLARITY);
    SENSOR_USLEEP(1000);

    sensor_if->MCLK(idx, 1, handle->mclk);
    SENSOR_USLEEP(5000);
    return SUCCESS;
}

static int pCus_poweroff(ms_cus_sensor* handle, u32 idx)
{
    ISensorIfAPI* sensor_if = handle->sensor_if_api;

    sensor_if->PowerOff(idx, !handle->pwdn_POLARITY);
    sensor_if->Reset(idx, handle->reset_POLARITY);
    SENSOR_USLEEP(1000);
    sensor_if->SetCSI_Clk(idx, CUS_CSI_CLK_DISABLE);
    sensor_if->MCLK(idx, 0, handle->mclk);
    return SUCCESS;
}

static int pCus_GetSensorID(ms_cus_sensor* handle, u32* id)
{
    int i, n;
    int table_length = ARRAY_SIZE(Sensor_id_table);
    I2C_ARRAY id_from_sensor[ARRAY_SIZE(Sensor_id_table)];

    for (n = 0; n < table_length; ++n) {
        id_from_sensor[n].reg = Sensor_id_table[n].reg;
        id_from_sensor[n].data = 0;
    }

    *id = 0;
    for (n = 0; n < 3; ++n) {
        if (SensorRegArrayR((I2C_ARRAY*)id_from_sensor, table_length) == SUCCESS)
            break;
    }
    if (n == 3)
        return FAIL;

    for (i = 0; i < table_length; ++i) {
        if (id_from_sensor[i].data != Sensor_id_table[i].data)
            return FAIL;
        *id = (*id << 8) | id_from_sensor[i].data;
    }

    SENSOR_DMSG("[%s] gc5603 id 0x%x\n", __FUNCTION__, (int)*id);
    return SUCCESS;
}

static int gc5603_SetPatternMode(ms_cus_sensor* handle, u32 mode)
{
    return SUCCESS;
}

static int pCus_init(ms_cus_sensor* handle)
{
    int i, cnt;

    for (i = 0; i < ARRAY_SIZE(Sensor_init_table); i++) {
        if (Sensor_init_table[i].reg == 0xffff) {
            msleep(Sensor_init_table[i].data);
            continue;
        }
        cnt = 0;
        while (SensorReg_Write(Sensor_init_table[i].reg, Sensor_init_table[i].data) != SUCCESS) {
            if (++cnt >= 10) {
                SENSOR_EMSG("[%s] write 0x%04x failed\n", __FUNCTION__, Sensor_init_table[i].reg);
                return FAIL;
            }
            msleep(10);
        }
    }
    return SUCCESS;
}

static int pCus_GetVideoResNum(ms_cus_sensor* handle, u32* ulres_num)
{
    *ulres_num = handle->video_res_supported.num_res;
    return SUCCESS;
}

static int pCus_GetVideoRes(ms_cus_sensor* handle, u32 res_idx, cus_camsensor_res** res)
{
    if (res_idx >= handle->video_res_supported.num_res)
        return FAIL;
    *res = &handle->video_res_supported.res[res_idx];
    return SUCCESS;
}

static int pCus_GetCurVideoRes(ms_cus_sensor* handle, u32* cur_idx, cus_camsensor_res** res)
{
    *cur_idx = handle->video_res_supported.ulcur_res;
    if (*cur_idx >= handle->video_res_supported.num_res)
        return FAIL;
    *res = &handle->video_res_supported.res[*cur_idx];
    return SUCCESS;
}

static int pCus_SetVideoRes(ms_cus_sensor* handle, u32 res_idx)
{
    if (res_idx >= handle->video_res_supported.num_res)
        return FAIL;
    if (res_idx == 0) {
        handle->video_res_supported.ulcur_res = 0;
        handle->pCus_sensor_init = pCus_init;
    }
    return SUCCESS;
}

static int pCus_GetOrien(ms_cus_sensor* handle, CUS_CAMSENSOR_ORIT* orit)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;
    *orit = params->orit;
    return SUCCESS;
}

static int pCus_SetOrien(ms_cus_sensor* handle, CUS_CAMSENSOR_ORIT orit)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;
    u16 bits;

    switch (orit) {
    case CUS_ORIT_M0F0:
        bits = 0;
        break;
    case CUS_ORIT_M1F0:
        bits = 1;
        break;
    case CUS_ORIT_M0F1:
        bits = 2;
        break;
    case CUS_ORIT_M1F1:
        bits = 3;
        break;
    default:
        return SUCCESS;
    }

    memcpy(params->tMirror_reg, mirror_reg, sizeof(mirror_reg));
    memcpy(params->tMirrorPost_reg, mirror_post_reg, sizeof(mirror_post_reg));
    params->tMirror_reg[0].data = bits; /* 0x022c */
    params->tMirror_reg[1].data = bits; /* 0x0063 */
    params->tMirror_reg[18].data = 0x60 | bits; /* 0x0a73 */
    params->orit = orit;
    params->orient_dirty = true;
    return SUCCESS;
}

static int pCus_GetFPS(ms_cus_sensor* handle)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;
    return params->expo.fps;
}

static void gc5603_update_vts(gc5603_params* params)
{
    u32 vts = params->expo.vts;

    if (params->expo.line > vts - EXPO_VTS_MARGIN)
        vts = params->expo.line + EXPO_VTS_MARGIN;
    params->tVts_reg[0].data = (vts >> 8) & 0x3f;
    params->tVts_reg[1].data = vts & 0xff;
}

static int pCus_SetFPS(ms_cus_sensor* handle, u32 fps)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;

    if (fps >= Preview_MIN_FPS && fps <= Preview_MAX_FPS)
        params->expo.vts = (vts_30fps * 30) / fps;
    else if (fps >= Preview_MIN_FPS * 1000 && fps <= Preview_MAX_FPS * 1000)
        params->expo.vts = (vts_30fps * 30000) / fps;
    else
        return FAIL;

    params->expo.fps = fps;
    gc5603_update_vts(params);
    params->dirty = true;
    return SUCCESS;
}

static int pCus_AEStatusNotify(ms_cus_sensor* handle, CUS_CAMSENSOR_AE_STATUS_NOTIFY status)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;

    if (status != CUS_FRAME_ACTIVE)
        return SUCCESS;

    if (params->orient_dirty) {
        SensorRegArrayW((I2C_ARRAY*)params->tMirror_reg, ARRAY_SIZE(mirror_reg));
        msleep(20);
        SensorRegArrayW((I2C_ARRAY*)params->tMirrorPost_reg, ARRAY_SIZE(mirror_post_reg));
        params->orient_dirty = false;
    }
    if (params->dirty) {
        SensorRegArrayW((I2C_ARRAY*)params->tGain_reg, ARRAY_SIZE(gain_reg));
        SensorRegArrayW((I2C_ARRAY*)params->tExpo_reg, ARRAY_SIZE(expo_reg));
        SensorRegArrayW((I2C_ARRAY*)params->tVts_reg, ARRAY_SIZE(vts_reg));
        params->dirty = false;
    }
    return SUCCESS;
}

static int pCus_GetAEUSecs(ms_cus_sensor* handle, u32* us)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;
    u32 lines;

    lines = (params->tExpo_reg[0].data & 0xff) | ((params->tExpo_reg[1].data & 0x3f) << 8);
    *us = (lines * Preview_line_period) / 1000;
    return SUCCESS;
}

static int pCus_SetAEUSecs(ms_cus_sensor* handle, u32 us)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;
    u32 lines = (1000 * us) / Preview_line_period;

    if (lines < 1)
        lines = 1;
    params->expo.line = lines;
    params->tExpo_reg[0].data = lines & 0xff;
    params->tExpo_reg[1].data = (lines >> 8) & 0x3f;
    gc5603_update_vts(params);
    params->dirty = true;
    return SUCCESS;
}

static int pCus_GetAEGain(ms_cus_sensor* handle, u32* gain)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;
    u32 again = 1024, dgain;
    int i;

    for (i = 0; i < GAIN_TABLE_SIZE; i++) {
        if (gain_table[i].r00b8 == params->tGain_reg[7].data && gain_table[i].r00b9 == params->tGain_reg[8].data) {
            again = gain_table[i].gain;
            break;
        }
    }
    dgain = (params->tGain_reg[9].data & 0xf) * 64 + (params->tGain_reg[10].data >> 2);
    *gain = (again * dgain) / 64;
    return SUCCESS;
}

/* Black-level trim, written straight to the sensor as the vendor does. */
static void gc5603_blc_write(ms_cus_sensor* handle, u16 coarse, u16 fine)
{
    SensorReg_Write(0x0455, coarse);
    SensorReg_Write(0x0456, coarse);
    SensorReg_Write(0x0451, fine);
    SensorReg_Write(0x0452, fine);
}

/*
 * The vendor driver reads a level from 0x0410/0x0414 on every gain change. It
 * rises with sensor temperature. By that level and the gain band (under 16x,
 * 32x, 64x, 80x, and above) it trims the black level in 0x0451/0x0452/0x0455/
 * 0x0456, and while the sensor stays hot it walks the usable analog gain table
 * down to 17 entries, giving them back as it cools. The thresholds and values
 * below are the vendor's.
 */
struct blc_step {
    u16 coarse, fine;
};

/* Per gain band 0..3; band 4 (80x and up) writes nothing. */
static const struct blc_step blc_cold27[4] = { { 4, 0x00 }, { 3, 0xe0 }, { 3, 0x60 }, { 2, 0xc0 } };
static const struct blc_step blc_cold11[4] = { { 4, 0x00 }, { 3, 0xf0 }, { 3, 0x80 }, { 3, 0x60 } };
static const struct blc_step blc_level3[4] = { { 4, 0x00 }, { 3, 0x50 }, { 3, 0x10 }, { 2, 0x90 } };
static const struct blc_step blc_level4[4] = { { 4, 0x00 }, { 3, 0x10 }, { 2, 0xb0 }, { 2, 0x70 } };
static const struct blc_step blc_level5[4] = { { 4, 0x00 }, { 2, 0xe0 }, { 2, 0x90 }, { 2, 0x50 } };
static const struct blc_step blc_level6[4] = { { 4, 0x00 }, { 2, 0xc0 }, { 2, 0x50 }, { 2, 0x30 } };

static int gc5603_gain_band(u32 gain)
{
    if (gain < 16 * 1024)
        return 0;
    if (gain < 32 * 1024)
        return 1;
    if (gain < 64 * 1024)
        return 2;
    if (gain < 80 * 1024)
        return 3;
    return 4;
}

static const struct blc_step* gc5603_level_table(u8 level)
{
    switch (level) {
    case 3:
        return blc_level3;
    case 4:
        return blc_level4;
    case 5:
        return blc_level5;
    case 6:
        return blc_level6;
    default:
        return NULL;
    }
}

enum temp_next { TEMP_SETTLE, TEMP_TRACK, TEMP_SELECT };

static void gc5603_temp_comp(ms_cus_sensor* handle, gc5603_params* params, u32 gain)
{
    volatile u16 lo = 0, hi = 0;
    const struct blc_step* table = NULL;
    enum temp_next next = TEMP_SETTLE;
    int band = gc5603_gain_band(gain);
    u16 level;

    SensorReg_Read(0x0410, &lo);
    SensorReg_Read(0x0414, &hi);
    level = lo | (hi << 8);

    if (hi == 1) {
        if (lo > 32) {
            params->temp_hot = 1;
            params->temp_level = 6;
            table = blc_level6;
            next = (band == 4) ? TEMP_TRACK : TEMP_SETTLE;
        }
    } else if (hi == 0) {
        if (lo > 69) {
            params->temp_hot = 1;
            params->temp_level = 5;
            table = blc_level5;
            next = (band == 4) ? TEMP_TRACK : TEMP_SETTLE;
        } else if (lo > 51) {
            params->temp_hot = 1;
            params->temp_level = 4;
            table = blc_level4;
            next = (band == 4) ? TEMP_TRACK : TEMP_SETTLE;
        } else if (lo > 40) {
            params->temp_hot = 1;
            params->temp_level = 3;
            table = blc_level3;
            next = (band == 4) ? TEMP_TRACK : TEMP_SETTLE;
        } else if (lo > 27) {
            table = blc_cold27;
        } else if (lo > 11) {
            if (params->temp_hot == 0) {
                table = blc_cold11;
            } else if (params->temp_hot == 1) {
                table = gc5603_level_table(params->temp_level);
                next = (table == NULL || band == 4) ? TEMP_TRACK : TEMP_SETTLE;
            } else {
                next = TEMP_SELECT;
            }
        }
    }

    if (table && band < 4)
        gc5603_blc_write(handle, table[band].coarse, table[band].fine);

    if (next == TEMP_SETTLE) {
        if (params->temp_hot == 1)
            next = TEMP_TRACK;
        else if (params->temp_hot != 0)
            next = TEMP_SELECT;
    }

    if (next == TEMP_TRACK) {
        if (level > 28) {
            if (params->gain_idx_count - 1 <= GAIN_IDX_COUNT_MIN - 1)
                params->gain_idx_count = GAIN_IDX_COUNT_MIN;
            else
                params->gain_idx_count--;
            return;
        }
        if (level > 15)
            return;
        if (params->gain_idx_count + 1 <= GAIN_TABLE_SIZE) {
            params->gain_idx_count++;
            return;
        }
        params->gain_idx_count = GAIN_TABLE_SIZE;
        params->temp_hot = 0;
        next = TEMP_SETTLE;
    }

    /* Cooled right down: forget the hot state and restore the full table. */
    if (next == TEMP_SETTLE && hi == 0 && lo <= 5) {
        params->gain_idx_count = GAIN_TABLE_SIZE;
        params->temp_level = 0;
        params->temp_hot = 0;
        gc5603_blc_write(handle, 4, 0);
    }
}

static int pCus_SetAEGain(ms_cus_sensor* handle, u32 gain)
{
    gc5603_params* params = (gc5603_params*)handle->private_data;
    const Gain_ARRAY* e;
    int i, last, sel;
    u32 dgain;

    params->expo.final_gain = gain;
    gc5603_temp_comp(handle, params, gain);

    if (gain < 8 * 1024)
        params->temp_hot = 0;
    if (gain > SENSOR_MAX_GAIN)
        gain = SENSOR_MAX_GAIN;
    if (gain < SENSOR_MIN_GAIN)
        gain = SENSOR_MIN_GAIN;

    last = params->gain_idx_count - 1;
    sel = last > 0 ? last : 0;
    for (i = 0; i < last; i++) {
        if (gain >= gain_table[i].gain && gain < gain_table[i + 1].gain) {
            sel = i;
            break;
        }
    }
    e = &gain_table[sel];

    dgain = (gain << 6) / e->gain;
    if (dgain > 128)
        dgain = 128;

    params->tGain_reg[0].data = 0x2d;
    params->tGain_reg[1].data = e->r0614;
    params->tGain_reg[2].data = e->r0615;
    params->tGain_reg[3].data = e->r0225;
    params->tGain_reg[4].data = 0x28;
    params->tGain_reg[5].data = e->r1467;
    params->tGain_reg[6].data = e->r1468;
    params->tGain_reg[7].data = e->r00b8;
    params->tGain_reg[8].data = e->r00b9;
    params->tGain_reg[9].data = dgain >> 6;
    params->tGain_reg[10].data = (dgain << 2) & 0xff;

    params->dirty = true;
    return SUCCESS;
}

static int pCus_GetAEMinMaxUSecs(ms_cus_sensor* handle, u32* min, u32* max)
{
    *min = 30;
    *max = 1000000 / Preview_MIN_FPS;
    return SUCCESS;
}

static int pCus_GetAEMinMaxGain(ms_cus_sensor* handle, u32* min, u32* max)
{
    *min = handle->sat_mingain;
    *max = SENSOR_MAX_GAIN;
    return SUCCESS;
}

static int gc5603_GetShutterInfo(struct __ms_cus_sensor* handle, CUS_SHUTTER_INFO* info)
{
    info->max = 1000000000 / Preview_MIN_FPS;
    info->min = Preview_line_period;
    info->step = Preview_line_period;
    return SUCCESS;
}

static int pCus_setCaliData_gain_linearity(ms_cus_sensor* handle, CUS_GAIN_GAP_ARRAY* pArray, u32 num)
{
    return SUCCESS;
}

int cus_camsensor_init_handle(ms_cus_sensor* drv_handle)
{
    ms_cus_sensor* handle = drv_handle;
    gc5603_params* params;

    if (!handle)
        return FAIL;
    if (handle->private_data == NULL) {
        SENSOR_EMSG("[%s] Private data is empty!\n", __FUNCTION__);
        return FAIL;
    }
    params = (gc5603_params*)handle->private_data;
    memcpy(params->tGain_reg, gain_reg, sizeof(gain_reg));
    memcpy(params->tExpo_reg, expo_reg, sizeof(expo_reg));
    memcpy(params->tVts_reg, vts_reg, sizeof(vts_reg));
    memcpy(params->tMirror_reg, mirror_reg, sizeof(mirror_reg));
    memcpy(params->tMirrorPost_reg, mirror_post_reg, sizeof(mirror_post_reg));

    strcpy(handle->model_id, "gc5603_MIPI");

    handle->isp_type = SENSOR_ISP_TYPE;
    handle->sif_bus = SENSOR_IFBUS_TYPE;
    handle->data_prec = SENSOR_DATAPREC;
    handle->data_mode = SENSOR_DATAMODE;
    handle->bayer_id = SENSOR_BAYERID;
    handle->RGBIR_id = SENSOR_RGBIRID;
    handle->orient = SENSOR_ORIT;
    handle->interface_attr.attr_mipi.mipi_lane_num = SENSOR_MIPI_LANE_NUM;
    handle->interface_attr.attr_mipi.mipi_data_format = CUS_SEN_INPUT_FORMAT_RGB;
    handle->interface_attr.attr_mipi.mipi_yuv_order = 0;
    handle->interface_attr.attr_mipi.mipi_hsync_mode = SENSOR_MIPI_HSYNC_MODE;
    handle->interface_attr.attr_mipi.mipi_hdr_mode = CUS_HDR_MODE_NONE;
    handle->interface_attr.attr_mipi.mipi_hdr_virtual_channel_num = 0;

    handle->video_res_supported.num_res = 1;
    handle->video_res_supported.ulcur_res = 0;
    handle->video_res_supported.res[0].width = Preview_WIDTH;
    handle->video_res_supported.res[0].height = Preview_HEIGHT;
    handle->video_res_supported.res[0].max_fps = Preview_MAX_FPS;
    handle->video_res_supported.res[0].min_fps = Preview_MIN_FPS;
    handle->video_res_supported.res[0].crop_start_x = 0;
    handle->video_res_supported.res[0].crop_start_y = 0;
    handle->video_res_supported.res[0].nOutputWidth = Preview_WIDTH;
    handle->video_res_supported.res[0].nOutputHeight = Preview_HEIGHT;
    sprintf(handle->video_res_supported.res[0].strResDesc, "2960x1666@30fps");

    handle->i2c_cfg.mode = SENSOR_I2C_LEGACY;
    handle->i2c_cfg.fmt = SENSOR_I2C_FMT;
    handle->i2c_cfg.address = SENSOR_I2C_ADDR;
    handle->i2c_cfg.speed = SENSOR_I2C_SPEED;

    handle->mclk = Preview_MCLK_SPEED;

    handle->pwdn_POLARITY = SENSOR_PWDN_POL;
    handle->reset_POLARITY = SENSOR_RST_POL;
    handle->VSYNC_POLARITY = SENSOR_VSYNC_POL;
    handle->HSYNC_POLARITY = SENSOR_HSYNC_POL;
    handle->PCLK_POLARITY = SENSOR_PCLK_POL;

    handle->ae_gain_delay = 2;
    handle->ae_shutter_delay = 2;
    handle->ae_gain_ctrl_num = 1;
    handle->ae_shutter_ctrl_num = 1;
    handle->sat_mingain = SENSOR_MIN_GAIN;

    handle->pCus_sensor_release = cus_camsensor_release_handle;
    handle->pCus_sensor_init = pCus_init;
    handle->pCus_sensor_poweron = pCus_poweron;
    handle->pCus_sensor_poweroff = pCus_poweroff;
    handle->pCus_sensor_GetSensorID = pCus_GetSensorID;
    handle->pCus_sensor_GetVideoResNum = pCus_GetVideoResNum;
    handle->pCus_sensor_GetVideoRes = pCus_GetVideoRes;
    handle->pCus_sensor_GetCurVideoRes = pCus_GetCurVideoRes;
    handle->pCus_sensor_SetVideoRes = pCus_SetVideoRes;
    handle->pCus_sensor_GetOrien = pCus_GetOrien;
    handle->pCus_sensor_SetOrien = pCus_SetOrien;
    handle->pCus_sensor_GetFPS = pCus_GetFPS;
    handle->pCus_sensor_SetFPS = pCus_SetFPS;
    handle->pCus_sensor_SetPatternMode = gc5603_SetPatternMode;
    handle->pCus_sensor_AEStatusNotify = pCus_AEStatusNotify;
    handle->pCus_sensor_GetAEUSecs = pCus_GetAEUSecs;
    handle->pCus_sensor_SetAEUSecs = pCus_SetAEUSecs;
    handle->pCus_sensor_GetAEGain = pCus_GetAEGain;
    handle->pCus_sensor_SetAEGain = pCus_SetAEGain;
    handle->pCus_sensor_GetAEMinMaxGain = pCus_GetAEMinMaxGain;
    handle->pCus_sensor_GetAEMinMaxUSecs = pCus_GetAEMinMaxUSecs;
    handle->pCus_sensor_setCaliData_gain_linearity = pCus_setCaliData_gain_linearity;
    handle->pCus_sensor_GetShutterInfo = gc5603_GetShutterInfo;

    params->expo.vts = vts_30fps;
    params->expo.fps = 30;
    params->expo.line = 100;
    params->orit = SENSOR_ORIT;
    params->temp_level = 0;
    params->temp_hot = 0;
    params->gain_idx_count = GAIN_TABLE_SIZE;
    params->dirty = false;
    params->orient_dirty = false;
    return SUCCESS;
}

static int cus_camsensor_release_handle(ms_cus_sensor* handle)
{
    return SUCCESS;
}

SENSOR_DRV_ENTRY_IMPL_END_EX(gc5603,
    cus_camsensor_init_handle,
    NULL,
    NULL,
    gc5603_params);

general/package/sigmastar-osdrv-sensors/0001-sigmastar-infinity6c-add-gc5603-driver.patch

new, 960 lines. This is how the driver reaches the build: a patch the sigmastar-osdrv-sensors package applies to its copy of openipc/sensors. Its body is the driver above, every line prefixed with +; checked identical. Its header:

diff --git a/sigmastar/infinity6c/sensor_gc5603_mipi.c b/sigmastar/infinity6c/sensor_gc5603_mipi.c
new file mode 100644
index 0000000..8b84864
--- /dev/null
+++ b/sigmastar/infinity6c/sensor_gc5603_mipi.c
@@ -0,0 +1,954 @@

general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar

modified, +6 / -0 lines. Loads the new driver when the U-Boot variable sensor is gc5603.

diff --git a/general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar b/general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar
index 4ffcb736..1ab609b0 100755
--- a/general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar
+++ b/general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar
@@ -48,6 +48,12 @@ set_sensor() {
 		gc4653|imx415|os04a10|sc4336p|sc401ai|sc501ai|sc830ai|sc850sl)
 			insmod $MODULE/sensor_${SENSOR}_mipi.ko chmap=1
 			;;
+		gc5603)
+			# 2-lane MIPI, 2960x1666@30. The driver comes from the vendor
+			# module on the AnjoyVision MC-L18D; its IQ file is the one that
+			# board ships for this sensor (its gc4023_day.bin).
+			insmod $MODULE/sensor_${SENSOR}_mipi.ko chmap=1
+			;;
 		gc8613ya|os03a10|os08a10|sc430ai|sc450ai|sc535hai|sc835hai|sp4329)
 			# Experimental sensors will be listed in a separate section. For contact: https://t.me/FlyRouter
 			insmod $MODULE/sensor_${SENSOR}_mipi.ko chmap=1

general/package/sigmastar-osdrv-infinity6c/files/sensor/configs/gc5603.bin

new, binary, 137904 bytes, sha256 f7ba8be4d8eb5bac18fc2aa15e4e6a1e19118e782341ae6a51374d35fa0a7bd8. Not code: the ISP tuning file. Byte-identical to the vendor's /config/iqfile/gc4023_day.bin from the flash dump, which is what the vendor firmware loads for this sensor.


4. Board package anjvision-mcl18d

general/package/anjvision-mcl18d/Config.in

new, 28 lines. Kconfig entry. Selecting it pulls in onvif-simple-server.

config BR2_PACKAGE_ANJVISION_MCL18D
	bool "anjvision-mcl18d"
	depends on BR2_PACKAGE_SIGMASTAR_OSDRV_INFINITY6C
	select BR2_PACKAGE_ONVIF_SIMPLE_SERVER
	help
	  Board support for the AnjoyVision MC-L18D camera module
	  (SSC377D + GC5603).

	  customizer.sh writes the board's pin map into majestic.yaml on
	  first boot (IR-cut GPIO 11/80, CDS light sensor GPIO 23, IR lamp
	  PWM4, white lamp PWM0, speaker enable GPIO 12), and muxes.sh
	  drives GPIO 10 and 61 to the vendor's boot levels. mcl18d-io
	  watches the reset button (GPIO 60; hold 5 s to restore factory
	  settings) and the alarm input (GPIO 44).

	  PTZ: ONVIF comes from onvif-simple-server on port 85 instead of
	  majestic, and its PTZ hooks run pelco-ptz, which drives the
	  zoom/focus lens board and the pan/tilt behind it on the D7 serial
	  port (/dev/ttyS2, 57600 baud): continuous moves, presets, home,
	  focus and iris. The board ignores every command unless autofocus
	  data keeps arriving, so S94mcl18d runs `pelco-ptz keepalive`,
	  one frame every 100 ms. This head has no absolute positions
	  other than its presets, so ONVIF AbsoluteMove and RelativeMove
	  are not offered. mcl18d-af focuses the lens once from majestic's
	  JPEG snapshots.

	  No sources are fetched; pelco-ptz is built from src/ in this
	  package.

general/package/anjvision-mcl18d/anjvision-mcl18d.mk

new, 31 lines. Builds pelco-ptz from src/ and installs every file.

################################################################################
#
# anjvision-mcl18d
#
################################################################################

ANJVISION_MCL18D_SITE = $(ANJVISION_MCL18D_PKGDIR)/src
ANJVISION_MCL18D_SITE_METHOD = local
ANJVISION_MCL18D_LICENSE = MIT

define ANJVISION_MCL18D_BUILD_CMDS
	$(MAKE) $(TARGET_CONFIGURE_OPTS) -C $(@D) pelco-ptz
endef

# customizer.sh and muxes.sh are the per-device seams S30customizer runs; they
# carry the same paths as OpenIPC/builder's devices/<board>/ files. onvif.conf
# goes in beside onvif-simple-server's own and customizer.sh puts it in place,
# so the two packages never install the same file.
define ANJVISION_MCL18D_INSTALL_TARGET_CMDS
	$(INSTALL) -m 644 -D $(ANJVISION_MCL18D_PKGDIR)/files/customizer.sh $(TARGET_DIR)/usr/share/openipc/customizer.sh
	$(INSTALL) -m 644 -D $(ANJVISION_MCL18D_PKGDIR)/files/muxes.sh $(TARGET_DIR)/usr/share/openipc/muxes.sh
	$(INSTALL) -m 755 -D $(ANJVISION_MCL18D_PKGDIR)/files/S94mcl18d $(TARGET_DIR)/etc/init.d/S94mcl18d
	$(INSTALL) -m 755 -D $(ANJVISION_MCL18D_PKGDIR)/files/mcl18d-io $(TARGET_DIR)/usr/sbin/mcl18d-io
	$(INSTALL) -m 755 -D $(@D)/pelco-ptz $(TARGET_DIR)/usr/sbin/pelco-ptz
	$(INSTALL) -m 755 -D $(ANJVISION_MCL18D_PKGDIR)/files/mcl18d-af $(TARGET_DIR)/usr/sbin/mcl18d-af
	$(INSTALL) -m 755 -D $(ANJVISION_MCL18D_PKGDIR)/files/onvif-passwd $(TARGET_DIR)/usr/sbin/onvif-passwd
	$(INSTALL) -m 644 -D $(ANJVISION_MCL18D_PKGDIR)/files/pelco-ptz.conf $(TARGET_DIR)/etc/pelco-ptz.conf
	$(INSTALL) -m 600 -D $(ANJVISION_MCL18D_PKGDIR)/files/onvif.conf $(TARGET_DIR)/etc/onvif.conf.mcl18d
endef

$(eval $(generic-package))

general/package/anjvision-mcl18d/files/customizer.sh

new, 46 lines. First boot: majestic pin map with night mode on (light sensor GPIO 23, IR lamp as GPIO 9), stream sizes, ONVIF switch-over, random ONVIF password.

#!/bin/sh
#
# AnjoyVision MC-L18D: majestic pin map, written once by S30customizer
# (it touches /etc/custom.ok; firstboot clears it and this runs again).
#
#   GPIO 11 / 80  D6 IR-cut. majestic's irCutPin1 opens the filter (night),
#                 irCutPin2 closes it (day); the vendor driver pulses GPIO 11
#                 for night and GPIO 80 for day.
#   GPIO 23       D5-1 CDSIN: the light board's own day/night output, 1 by day
#                 and 0 at night, read as a plain level. In the mode this unit
#                 shipped in ("Passive") the vendor judges day and night by it
#                 alone, and the board lights its IR LEDs itself in the dark;
#                 the SAR ADC path in media_server is for other customers.
#   PWM4          D5-3 infrared lamp (PAD_SPI0_CZ; the wiring sheet says PWM1).
#                 The vendor's other modes hold it fully on at night. This
#                 majestic brings up no PWM lamp on infinity6c, so the pad is
#                 the camera light as a plain GPIO (9) instead: high at night.
#   PWM0          D5-4 white/warm lamp (PAD_PWM0).
#   GPIO 12       D7-4 SPKEN, speaker amplifier enable.

cli -s .nightMode.irCutPin1 11
cli -s .nightMode.irCutPin2 80
cli -s .nightMode.lightSensorPin 23
cli -s .nightMode.lightMonitor true
cli -s .nightMode.backlightPin 9
cli -s .nightMode.irLightPwmChannel 4
cli -s .nightMode.whiteLightPwmChannel 0
cli -s .nightMode.irCut auto
cli -s .nightMode.backlight auto
cli -s .nightMode.whiteLight auto
cli -s .audio.speakerPin 12

# ONVIF, with PTZ, is onvif_simple_server on port 85 (onvif.conf, pelco-ptz),
# so majestic's own ONVIF service stands down and does not answer discovery
# for the same camera. The ONVIF profiles name stream=0 at 2560x1440 and
# stream=1 at 640x360.
cli -s .onvif.enabled false
cli -s .video0.size 2560x1440
cli -s .video1.enabled true
cli -s .video1.size 640x360

# A random ONVIF password until the owner sets theirs with onvif-passwd: the
# camera never answers ONVIF with a password anyone else knows.
pass=$(hexdump -n 9 -e '9/1 "%02x"' /dev/urandom)
sed "s/^password=.*/password=$pass/" /etc/onvif.conf.mcl18d > /etc/onvif.conf
chmod 600 /etc/onvif.conf

general/package/anjvision-mcl18d/files/muxes.sh

new, 16 lines. Every boot: GPIO 10 (red/blue light) and 61 (active-low warning light) to the vendor's levels.

#!/bin/sh
#
# AnjoyVision MC-L18D: the output levels the vendor firmware drives at every
# boot (libtools.so gpio_init_by_array). Run by S30customizer, before majestic.
#
#   GPIO 10  PAD_SPI0_CK  D7-5 red/blue light IO (vendor alarm output 1)
#   GPIO 61  PAD_SR_IO01  vendor GPIO type 12 (GetLedBrGpioPort): an active-low
#                         warning-light output that mainctrl pulls low on alarm;
#                         1 is its idle level. Not a light-board enable.

for pin_level in 10:1 61:1; do
	pin=${pin_level%:*}
	[ -d "/sys/class/gpio/gpio$pin" ] || echo "$pin" > /sys/class/gpio/export
	echo out > "/sys/class/gpio/gpio$pin/direction"
	echo "${pin_level#*:}" > "/sys/class/gpio/gpio$pin/value"
done

general/package/anjvision-mcl18d/files/S94mcl18d

new, 59 lines. Init script: starts mcl18d-io, the lens-board keep-alive (pelco-ptz keepalive) and ONVIF discovery.

#!/bin/sh
#
# AnjoyVision MC-L18D: run mcl18d-io, which watches the reset button and the
# alarm input; `pelco-ptz keepalive`, without which the lens board and the
# pan/tilt behind it ignore every command (/etc/pelco-ptz.conf); and
# wsd_simple_server, which answers ONVIF discovery for onvif_simple_server
# (S96onvifserver). The pin map and boot levels are in
# /usr/share/openipc/customizer.sh and muxes.sh.

WSD_PID=/var/run/wsd_simple_server.pid
KEEPALIVE_PID=/var/run/pelco-keepalive.pid

conf_value() {
	awk -F= -v k="$1" '$1 == k { print $2; exit }' /etc/onvif.conf
}

# Discovery advertises the camera's address, which DHCP may not have handed out
# yet this early in boot: wait for one in the background, up to a minute.
start_wsd() {
	[ -f /etc/onvif.conf ] || return
	(
		ifs=$(conf_value ifs)
		i=0
		while [ $i -lt 60 ] && ! ip -4 addr show dev "$ifs" 2>/dev/null | grep -q "inet "; do
			i=$((i + 1))
			sleep 1
		done
		wsd_simple_server -i "$ifs" -x "http://%s:$(conf_value port)/onvif/device_service" \
			-m "$(conf_value model)" -n "$(conf_value manufacturer)" -p "$WSD_PID"
	) &
}

case "$1" in
	start)
		echo "Starting mcl18d-io..."
		start-stop-daemon -S -b -m -p /var/run/mcl18d-io.pid -x /usr/sbin/mcl18d-io
		start-stop-daemon -S -b -m -p "$KEEPALIVE_PID" -x /usr/sbin/pelco-ptz -- keepalive
		start_wsd
		;;

	stop)
		start-stop-daemon -K -q -p /var/run/mcl18d-io.pid
		rm -f /var/run/mcl18d-io.pid
		start-stop-daemon -K -q -p "$KEEPALIVE_PID"
		rm -f "$KEEPALIVE_PID"
		[ -f "$WSD_PID" ] && kill "$(cat "$WSD_PID")" 2>/dev/null
		rm -f "$WSD_PID"
		;;

	restart)
		"$0" stop
		"$0" start
		;;

	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

general/package/anjvision-mcl18d/files/mcl18d-io

new, 57 lines. Reset button (hold 5 s = factory reset) and alarm input.

#!/bin/sh
#
# MC-L18D reset button and alarm input.
#
# The level each input reads at start is taken as its idle level, because the
# vendor firmware does not record the polarity of either.
#
#   Reset button (GPIO 60): held 5 s, restores factory settings (firstboot).
#   Alarm input (GPIO 44):  each change is logged, and /etc/mcl18d/alarm-in is
#                           run with "active" or "idle" if it exists.

RESET_PIN=60
ALARM_PIN=44
HOLD_TICKS=50 # 100 ms ticks, 5 s
ALARM_HOOK=/etc/mcl18d/alarm-in

gpio_in() {
	[ -d "/sys/class/gpio/gpio$1" ] || echo "$1" > /sys/class/gpio/export
	echo in > "/sys/class/gpio/gpio$1/direction"
}

gpio_in $RESET_PIN
gpio_in $ALARM_PIN

reset_value=/sys/class/gpio/gpio$RESET_PIN/value
alarm_value=/sys/class/gpio/gpio$ALARM_PIN/value
reset_idle=$(cat $reset_value)
alarm_idle=$(cat $alarm_value)
alarm_last=$alarm_idle
held=0

logger -t mcl18d "IO_WATCH_STARTED reset idle=$reset_idle alarm idle=$alarm_idle"

while true; do
	if [ "$(cat $reset_value)" != "$reset_idle" ]; then
		held=$((held + 1))
		if [ $held -eq $HOLD_TICKS ]; then
			logger -t mcl18d "RESET_BUTTON held 5 s, restoring factory settings"
			firstboot
		fi
	else
		[ $held -gt 0 ] && [ $held -lt $HOLD_TICKS ] &&
			logger -t mcl18d "RESET_BUTTON released after $((held * 100)) ms, ignored"
		held=0
	fi

	alarm_now=$(cat $alarm_value)
	if [ "$alarm_now" != "$alarm_last" ]; then
		alarm_last=$alarm_now
		state=idle
		[ "$alarm_now" != "$alarm_idle" ] && state=active
		logger -t mcl18d "ALARM_IN $state"
		[ -x "$ALARM_HOOK" ] && "$ALARM_HOOK" "$state" &
	fi

	usleep 100000
done

general/package/anjvision-mcl18d/files/onvif.conf

new, 70 lines. onvif-simple-server configuration, PTZ hooks pointing at pelco-ptz; AbsoluteMove/RelativeMove left out because this head ignores them. Installed as /etc/onvif.conf.mcl18d.

# AnjoyVision MC-L18D: onvif_simple_server, with PTZ through pelco-ptz.
# customizer.sh copies this to /etc/onvif.conf on first boot and puts a random
# password in it; set your own with `onvif-passwd`. S96onvifserver fills in
# firmware_ver, hardware_id, serial_num and ifs at every start.
#
# Use the same user and password as the camera's root login: ONVIF clients
# reuse the ONVIF credentials for the RTSP stream, which majestic checks
# against root.

# General
model=MC-L18D
manufacturer=OpenIPC
firmware_ver=
hardware_id=
serial_num=
ifs=eth0
port=85
scope=onvif://www.onvif.org/Profile/Streaming
scope=onvif://www.onvif.org/Profile/T
user=root
password=

#Profile 0
name=Profile_0
width=2560
height=1440
url=rtsp://%s/stream=0
snapurl=http://%s/image.jpg
type=H264

#Profile 1
name=Profile_1
width=640
height=360
url=rtsp://%s/stream=1
snapurl=http://%s/image.jpg?width=640&height=360
type=H264

#PTZ
# Pelco-D on the D7 connector's serial port (/etc/pelco-ptz.conf). The ranges
# are the generic space pelco-ptz maps to the head: pan -1..1 is -180..180
# degrees, tilt -1..1 is -90..90 degrees (up positive), zoom 0..1 wide..tele.
ptz=1
min_step_x=-1
max_step_x=1
min_step_y=-1
max_step_y=1
min_step_z=0
max_step_z=1
get_position=/usr/sbin/pelco-ptz position
is_moving=/usr/sbin/pelco-ptz moving
move_left=/usr/sbin/pelco-ptz move left %f
move_right=/usr/sbin/pelco-ptz move right %f
move_up=/usr/sbin/pelco-ptz move up %f
move_down=/usr/sbin/pelco-ptz move down %f
move_in=/usr/sbin/pelco-ptz move in %f
move_out=/usr/sbin/pelco-ptz move out %f
move_stop=/usr/sbin/pelco-ptz stop
move_preset=/usr/sbin/pelco-ptz preset goto %d
goto_home_position=/usr/sbin/pelco-ptz home
set_preset=/usr/sbin/pelco-ptz preset set %s
set_home_position=/usr/sbin/pelco-ptz sethome
remove_preset=/usr/sbin/pelco-ptz preset remove %d
# This head ignores Pelco-D's set-position commands (0x4B/0x4D/0x4F) and
# never answers the position queries, so an AbsoluteMove or RelativeMove would
# be acknowledged and do nothing. Its absolute positions are its presets, which
# it returns to on its own. For a head that does implement them:
#jump_to_abs=/usr/sbin/pelco-ptz abs %f %f %f
#jump_to_rel=/usr/sbin/pelco-ptz rel %f %f %f
get_presets=/usr/sbin/pelco-ptz preset list

general/package/anjvision-mcl18d/files/onvif-passwd

new, 27 lines. Sets the ONVIF password.

#!/bin/sh
#
# Set the ONVIF password in /etc/onvif.conf. Give the camera's root password:
# ONVIF clients use the same credentials for the RTSP stream.

CONF=/etc/onvif.conf

if [ -n "$1" ]; then
	pass=$1
else
	printf "New ONVIF password: "
	stty -echo 2>/dev/null
	read -r pass
	stty echo 2>/dev/null
	echo
fi

if [ -z "$pass" ]; then
	echo "Empty password, nothing changed." >&2
	exit 1
fi

tmp=$CONF.tmp
PASS="$pass" awk '/^password=/ { print "password=" ENVIRON["PASS"]; next } { print }' "$CONF" > "$tmp" &&
	chmod 600 "$tmp" && mv "$tmp" "$CONF" || exit 1
logger -t onvif-passwd "ONVIF_PASSWORD_CHANGED"
echo "ONVIF password set."

general/package/anjvision-mcl18d/files/pelco-ptz.conf

new, 38 lines. pelco-ptz settings: port, 57600 baud, address, mounting, presets, keep-alive interval.

# pelco-ptz: the zoom/focus lens board, and any Pelco-D head, on the
# MC-L18D's D7 serial port.
#
# D7 is a 3.3 V UART (the SoC's FUART, /dev/ttyS2). The lens board takes
# Pelco-D at 57600 baud, address 1: the vendor firmware switches the port to
# 57600 whenever its /opt/ch/af.flag exists, as it does on this camera, and
# ignores its own 2400 PTZ setting (AF-BOARD-PROTOCOL.md). A pan/tilt head on
# the same wires must run at 57600 too. Without the lens board, 2400 is a
# factory-fresh head's rate; match the head's DIP switches. Most heads take
# RS-485, which needs a 3.3 V TTL to RS-485 adapter between D7 and the head.
port=/dev/ttyS2
baud=57600
address=1

# Mounting. Set an invert to 1 when the head moves the opposite way to what
# was asked, e.g. a ceiling mount. tilt_min/tilt_max are the head's travel in
# degrees from the horizon, up positive.
pan_invert=0
tilt_invert=0
tilt_min=-90
tilt_max=90

# Preset 1 is the ONVIF home position; ONVIF presets use 2..max_preset. Many
# heads give presets above 32 special meanings (95 opens the menu on some).
home_preset=1
max_preset=32

# How long an absolute move or a preset counts as "moving", and how long to
# wait for the head to answer a position query.
settle_ms=3000
query_timeout_ms=300

# The lens board ignores every frame, pan and tilt included, unless it has had
# autofocus data recently: the vendor firmware streams it at frame rate, and
# without it the board dozes off within seconds. S94mcl18d runs
# `pelco-ptz keepalive`, which sends one such frame every keepalive_ms. 0 turns
# it off, for a head on D7 with no lens board behind it.
keepalive_ms=100

general/package/anjvision-mcl18d/files/mcl18d-af

new, 309 lines. One-shot contrast autofocus through pelco-ptz and majestic snapshots: a timed sweep past focus, then a one-way stepped approach.

#!/bin/sh
#
# mcl18d-af: one-shot autofocus for the MC-L18D's lens board.
#
# The board's own autofocus needs a frame of ISP focus statistics for every
# video frame (AF-BOARD-PROTOCOL.md section 2), and majestic does not export
# those. So this drives the focus motor itself through pelco-ptz, and judges
# sharpness by the size of a JPEG snapshot: at a fixed quality, a sharper
# picture has more fine detail and compresses less. On the camera, 2026-10-29,
# a sharp snapshot was nearly three times the size of a blurred one, against
# 0.1-0.6% between two snapshots of a still scene.
#
# The motor is slow: focus lay 19 s of motor time from where it started and
# the sharp band was about 1.5 s wide, so short steps from a blurred start
# climb noise. So it first sweeps: it runs the motor without stopping, takes
# snapshots as fast as they come, and stops once the picture has risen well
# above where it began and then fallen back from its best, which is focus
# just passed. If the picture gets clearly worse over the first 1.5 s or more
# it turns round, and if a whole sweep finds nothing it sweeps the other way.
# The second sweep never turns: a snapshot shows the lens a little after the
# fact, so just after a reversal the picture goes on getting worse for a
# moment, and on the camera that once made the second sweep give up at once.
#
# Then it finishes without ever turning round, because each reversal loses
# some travel to gear backlash and the first version, which climbed back and
# forth, ended short of focus for that reason. It runs back past the best
# snapshot by a margin, then steps forward the way the sweep went, measuring
# after each step, and stops on the first step that is worse: the lens rests
# one step past the sharpest point. If the very first step is already worse,
# the margin was not enough, and it backs off further and tries again.
#
# usage: mcl18d-af [-u USER:PASS] [-c XxYxWxH|full] [-s STEP_MS] [-b BACK_MS]
#                  [-n SAMPLES] [-w SETTLE_MS] [-g PERMILLE] [-t SWEEP_S]
#                  [-a URL]
#
#   -u  majestic's login, root and its password. Default: user= and password=
#       from /etc/onvif.conf, which onvif-passwd sets to root's password.
#   -c  region to judge, in snapshot pixels. Default: the middle third, or the
#       full frame where majestic refuses a crop (it does on this SoC).
#   -s  final approach step in ms of motor time (150).
#   -b  how far past the best snapshot to back off before approaching (1000).
#   -n  snapshots averaged per measurement (2); -w wait after a step (300 ms).
#   -g  how much, in thousandths, a step must change the picture to count (5).
#   -t  longest sweep one way, in seconds of motor time (45).

url=http://127.0.0.1/image.jpg
auth=
crop=
step_ms=150
back_ms=1000
samples=2
settle_ms=300
gain_permille=5
sweep_s=45
tries=3
# A sweep has found focus once the picture rose RISE thousandths above its
# start and then fell DROP below its best on two snapshots running; it turns
# round early if the picture falls TURN below its start without rising.
rise_permille=50
drop_permille=30
turn_permille=30
turn_cs=150

# The header above is stripped from the shipped copy, so the usage is text.
usage() {
	cat >&2 <<EOF
usage: mcl18d-af [-u USER:PASS] [-c XxYxWxH|full] [-s STEP_MS] [-b BACK_MS]
                 [-n SAMPLES] [-w SETTLE_MS] [-g PERMILLE] [-t SWEEP_S] [-a URL]
  -u  majestic's login (default: user/password in /etc/onvif.conf)
  -c  region to judge, in snapshot pixels (default: the middle third)
  -s  final approach step, ms of motor time ($step_ms)
  -b  back-off past the best snapshot before approaching, ms ($back_ms)
  -n  snapshots averaged per measurement ($samples)
  -w  wait after each step before measuring, ms ($settle_ms)
  -g  thousandths a step must change the picture to count ($gain_permille)
  -t  longest sweep one way, seconds of motor time ($sweep_s)
  -a  snapshot URL ($url)
EOF
	exit 1
}

while getopts "u:c:s:b:n:w:g:t:a:h" opt; do
	case $opt in
	u) auth=$OPTARG ;;
	c) crop=$OPTARG ;;
	s) step_ms=$OPTARG ;;
	b) back_ms=$OPTARG ;;
	n) samples=$OPTARG ;;
	w) settle_ms=$OPTARG ;;
	g) gain_permille=$OPTARG ;;
	t) sweep_s=$OPTARG ;;
	a) url=$OPTARG ;;
	*) usage ;;
	esac
done

for v in "$step_ms" "$back_ms" "$samples" "$settle_ms" "$gain_permille" "$sweep_s"; do
	case $v in
	'' | *[!0-9]*) echo "not a number: $v" >&2; exit 1 ;;
	esac
done
[ "$samples" -ge 1 ] && [ "$step_ms" -ge 1 ] || { echo "-n and -s must be at least 1" >&2; exit 1; }

log() {
	echo "$*"
	logger -t mcl18d-af "$*"
}

if [ -z "$auth" ] && [ -r /etc/onvif.conf ]; then
	user=$(sed -n 's/^user=//p' /etc/onvif.conf)
	pass=$(sed -n 's/^password=//p' /etc/onvif.conf)
	[ -n "$user" ] && auth=$user:$pass
fi

if [ -z "$crop" ]; then
	size=$(cli -g .video0.size 2>/dev/null)
	w=${size%x*}
	h=${size#*x}
	case $w$h in
	'' | *[!0-9]*) crop=full ;;
	*) crop=$((w / 3))x$((h / 3))x$((w / 3))x$((h / 3)) ;;
	esac
fi
[ "$crop" = full ] || url="$url?crop=$crop"

# Bytes in one snapshot; fails on any HTTP error.
snap() {
	if [ -n "$auth" ]; then
		curl -s -f --anyauth -u "$auth" -o /dev/null -w '%{size_download}' "$url"
	else
		curl -s -f -o /dev/null -w '%{size_download}' "$url"
	fi
}

measure() {
	total=0
	i=0
	while [ $i -lt "$samples" ]; do
		s=$(snap) || return 1
		total=$((total + s))
		i=$((i + 1))
	done
	echo $((total / samples))
}

stop() {
	pelco-ptz stop >/dev/null 2>&1
}

# Run the focus motor one way for $2 ms, then let the picture settle.
pulse() {
	pelco-ptz focus "$1" || return 1
	usleep $(($2 * 1000))
	stop
	usleep $((settle_ms * 1000))
}

# Centiseconds since boot.
now_cs() {
	read -r up _ < /proc/uptime
	echo "${up%.*}${up#*.}"
}

opposite() {
	if [ "$1" = far ]; then echo near; else echo far; fi
}

# Run the motor $1-ward for up to $2 centiseconds, snapshotting as it goes;
# $3 is 1 if it may turn round. Returns 0 with peak_cs (when the best snapshot
# was taken, from the start of the sweep) and run_cs (how long the motor ran)
# once focus has been passed, 2 if the picture got clearly worse from the
# start, 1 if the time ran out, and 3 if a snapshot failed.
sweep() {
	sw_base=$(snap) || return 3
	pelco-ptz focus "$1" || return 3
	sw_t0=$(now_cs)
	sw_best=$sw_base
	peak_cs=0
	sw_low=0
	sw_n=0
	while :; do
		sw_a=$(now_cs)
		sw_s=$(snap) || { stop; return 3; }
		sw_b=$(now_cs)
		sw_t=$(((sw_a + sw_b) / 2 - sw_t0))
		sw_n=$((sw_n + 1))
		if [ "$sw_s" -gt "$sw_best" ]; then
			sw_best=$sw_s
			peak_cs=$sw_t
			sw_low=0
		elif [ $((sw_best * 1000)) -gt $((sw_base * (1000 + rise_permille))) ] &&
			[ $((sw_s * 1000)) -lt $((sw_best * (1000 - drop_permille))) ]; then
			sw_low=$((sw_low + 1))
		else
			sw_low=0
		fi
		if [ $sw_low -ge 2 ]; then
			stop
			run_cs=$(($(now_cs) - sw_t0))
			log "AF_SWEEP $1 found best=$sw_best at ${peak_cs}0ms, ran ${run_cs}0ms"
			return 0
		fi
		if [ "$3" = 1 ] && [ $sw_n -ge 3 ] && [ $sw_t -ge $turn_cs ] &&
			[ $((sw_best * 1000)) -le $((sw_base * (1000 + rise_permille))) ] &&
			[ $((sw_s * 1000)) -lt $((sw_base * (1000 - turn_permille))) ]; then
			stop
			run_cs=$(($(now_cs) - sw_t0))
			log "AF_SWEEP $1 getting worse after ${run_cs}0ms, turning"
			return 2
		fi
		if [ $(($(now_cs) - sw_t0)) -ge "$2" ]; then
			stop
			run_cs=$(($(now_cs) - sw_t0))
			log "AF_SWEEP $1 no focus in ${run_cs}0ms"
			return 1
		fi
	done
}

# Step $1-ward until a step makes the picture worse. Returns 0 having passed
# the sharpest point (or after enough steps to cross the back-off twice), 2 if
# the first step that changed anything made it worse, 3 on a failure.
steps=0
approach() {
	ap_best=$(measure) || return 3
	ap_rose=0
	ap_n=0
	ap_max=$((back_ms * 2 / step_ms + 10))
	while [ $ap_n -lt $ap_max ]; do
		pulse "$1" "$step_ms" || return 3
		ap_s=$(measure) || return 3
		ap_n=$((ap_n + 1))
		steps=$((steps + 1))
		if [ $((ap_s * 1000)) -gt $((ap_best * (1000 + gain_permille))) ]; then
			log "AF_STEP $1 ${step_ms}ms sharpness=$ap_s better"
			ap_best=$ap_s
			ap_rose=1
		elif [ $((ap_s * 1000)) -lt $((ap_best * (1000 - gain_permille))) ]; then
			log "AF_STEP $1 ${step_ms}ms sharpness=$ap_s worse"
			[ $ap_rose -eq 1 ] && return 0
			return 2
		else
			log "AF_STEP $1 ${step_ms}ms sharpness=$ap_s same"
		fi
	done
	return 0
}

trap stop EXIT
trap 'exit 130' INT TERM

if ! best=$(measure) || [ "$best" -eq 0 ]; then
	if [ "$crop" != full ] && url=${url%%\?*} && best=$(measure) && [ "$best" -gt 0 ]; then
		log "AF_CROP_REFUSED $crop, judging the full frame"
		crop=full
	else
		log "AF_SNAPSHOT_FAILED $url: is majestic running, and is -u root:PASSWORD right?"
		exit 2
	fi
fi
log "AF_START sharpness=$best region=$crop"

# Find focus coarsely: far first, then the other way over the whole range.
dir=far
sweep far $((sweep_s * 100)) 1
rc=$?
if [ $rc -eq 1 ] || [ $rc -eq 2 ]; then
	if [ $rc -eq 2 ]; then
		limit=$((run_cs + sweep_s * 100))
	else
		limit=$((run_cs + sweep_s * 200))
	fi
	dir=near
	sweep near $limit 0
	rc=$?
fi
case $rc in
0) ;;
3)
	log "AF_SNAPSHOT_FAILED $url"
	exit 2
	;;
*)
	log "AF_NO_DETAIL no focus found sweeping both ways: nothing in the picture to focus on"
	exit 3
	;;
esac

# Back off past the best snapshot, then approach it the way the sweep went.
back=$(opposite $dir)
off=$(((run_cs - peak_cs) * 10 + back_ms))
t=0
while :; do
	log "AF_BACK $back ${off}ms"
	pulse "$back" "$off" || exit 2
	approach "$dir"
	rc=$?
	[ $rc -eq 3 ] && { log "AF_SNAPSHOT_FAILED $url"; exit 2; }
	[ $rc -eq 0 ] && break
	t=$((t + 1))
	if [ $t -ge $tries ]; then
		log "AF_LOST focus not found again after $tries back-offs"
		exit 2
	fi
	off=$back_ms
done

s=$(measure) || s=?
log "AF_DONE sharpness=$s best_seen=$ap_best steps=$steps"

general/package/anjvision-mcl18d/src/pelco.h

new, 144 lines. Pelco-D frames and coordinate mapping: interface.

// Pelco-D: frames, the extended absolute-position commands, and the mapping
// between ONVIF's generic coordinate space and the head's angles.
//
// Pure: no I/O, no clock, no files, so tests/pelco_test.c pins every byte.
//
// The generic space this tool offers ONVIF (onvif.conf min/max_step):
//   pan  x  -1..1  is  -180..+180 degrees from the head's zero, wrapping
//   tilt y  -1..1  is   -90.. +90 degrees, up positive, clamped to the head
//   zoom z   0..1  is  Pelco-D's zoom position 0..65535 (wide..tele)
// A relative move uses the same scale: dx 0.5 turns the head 90 degrees.

#ifndef PELCO_H
#define PELCO_H

#include <stdbool.h>
#include <stdint.h>

#define PELCO_FRAME_LEN 7
#define PELCO_SYNC 0xff

// Command 2 movement bits.
#define PELCO_RIGHT 0x02
#define PELCO_LEFT 0x04
#define PELCO_UP 0x08
#define PELCO_DOWN 0x10
#define PELCO_TELE 0x20
#define PELCO_WIDE 0x40
#define PELCO_FOCUS_FAR 0x80

// Command 1 lens bits.
#define PELCO_FOCUS_NEAR 0x01
#define PELCO_IRIS_OPEN 0x02
#define PELCO_IRIS_CLOSE 0x04

// Command 2 opcodes (command 1 is 0 for all of them).
#define PELCO_SET_PRESET 0x03
#define PELCO_CLEAR_PRESET 0x05
#define PELCO_GOTO_PRESET 0x07
#define PELCO_SET_PAN 0x4b
#define PELCO_SET_TILT 0x4d
#define PELCO_SET_ZOOM 0x4f
#define PELCO_QUERY_PAN 0x51
#define PELCO_QUERY_TILT 0x53
#define PELCO_QUERY_ZOOM 0x55
#define PELCO_REPLY_PAN 0x59
#define PELCO_REPLY_TILT 0x5b
#define PELCO_REPLY_ZOOM 0x5d

// Pan/tilt speed byte: 0x3f is the top rate; 0x40 ("turbo") is not used.
#define PELCO_SPEED_MAX 0x3f

// A frame that moves only the lens (zoom, focus, iris) carries a speed in both
// data bytes, as the vendor firmware sends it to the MC-L18D's lens board:
// the zoom speed, or 0x30 for focus and iris (AF-BOARD-PROTOCOL.md section 1).
#define PELCO_LENS_SPEED 0x30

// How the head is mounted.
typedef struct {
    bool pan_invert;   // the head turns right when told left
    bool tilt_invert;  // the head looks up when told down
    double tilt_min;   // lowest tilt the head reaches, degrees (negative is down)
    double tilt_max;   // highest tilt, degrees
} PelcoGeom;

// One sync, address, two command bytes, two data bytes and the checksum: the
// sum of address..data2, modulo 256.
void pelco_frame(uint8_t out[PELCO_FRAME_LEN], uint8_t addr, uint8_t c1,
                 uint8_t c2, uint8_t d1, uint8_t d2);

// ONVIF speed 0..1 to a Pelco speed byte: 0 for none, else 1..0x3f.
uint8_t pelco_speed(double v);

// Which way each axis is moving: pan -1 left, +1 right; tilt +1 up, -1 down;
// zoom +1 tele, -1 wide; focus +1 far, -1 near; iris +1 open, -1 close; 0
// still. Speeds are Pelco speed bytes; a zoom speed of 0 sends PELCO_LENS_SPEED.
typedef struct {
    int pan, tilt, zoom, focus, iris;
    uint8_t pan_speed, tilt_speed, zoom_speed;
} PelcoMotion;

// The one frame that carries all of `m`: Pelco-D sets the whole motion at
// once, so a diagonal or a zoom while panning has to be a single frame.
void pelco_motion_frame(uint8_t out[PELCO_FRAME_LEN], uint8_t addr,
                        const PelcoMotion *m, const PelcoGeom *g);

// Continuous moves arrive one axis per call (onvif_simple_server runs
// move_right and then move_up for one diagonal request). The state keeps when
// each axis was last set: an axis set within PELCO_COMBINE_MS of the call is
// part of the same request and kept, an older one is from an earlier request
// and stopped, which is what ONVIF's "the new velocity replaces the old" asks.
#define PELCO_COMBINE_MS 300
enum PelcoAxis {
    PELCO_AXIS_PAN,
    PELCO_AXIS_TILT,
    PELCO_AXIS_ZOOM,
    PELCO_AXIS_FOCUS,
    PELCO_AXIS_IRIS,
    PELCO_AXES
};
typedef struct {
    PelcoMotion m;
    long long ms[PELCO_AXES];  // when each axis was last set
} PelcoMoveState;

void pelco_state_move(PelcoMoveState *s, enum PelcoAxis axis, int dir,
                      uint8_t speed, long long now_ms);
bool pelco_state_moving(const PelcoMoveState *s);

// Generic coordinates to the head's absolute values (hundredths of a degree,
// 0..35999, for pan and tilt; 0..65535 for zoom) and back.
uint16_t pelco_pan_value(double x, const PelcoGeom *g);
uint16_t pelco_tilt_value(double y, const PelcoGeom *g);
uint16_t pelco_zoom_value(double z);
double pelco_pan_generic(uint16_t v, const PelcoGeom *g);
double pelco_tilt_generic(uint16_t v, const PelcoGeom *g);
double pelco_zoom_generic(uint16_t v);

// A position after a relative move: pan wraps around, tilt and zoom stop at
// the head's limits.
double pelco_pan_add(double x, double dx);
double pelco_tilt_add(double y, double dy, const PelcoGeom *g);
double pelco_zoom_add(double z, double dz);

// The frame that sets one axis to `value`, or asks for it.
void pelco_value_frame(uint8_t out[PELCO_FRAME_LEN], uint8_t addr, uint8_t op,
                       uint16_t value);

// Find a reply to a position query in `buf` (bytes as read off the wire, any
// noise before it skipped): sync, our address, 0, the reply opcode, the value,
// a good checksum. True and *value set when one is there.
bool pelco_find_reply(const uint8_t *buf, int n, uint8_t addr, uint8_t reply_op,
                      uint16_t *value);

// The MC-L18D's lens board, and the pan/tilt it drives, ignore every Pelco-D
// frame until they have seen several of the autofocus data frames the vendor
// firmware streams at frame rate, and go back to sleep some seconds after they
// stop (AF-BOARD-PROTOCOL.md section 2). This is one such frame, CAfV2: header
// 51 01 04 78 01 11, two focus values, gain, the stream-width class, a raw
// statistic, IR-cut, IR and white lamp levels, and the sum of bytes 0..16.
// The values are constant: nothing here feeds the board's autofocus.
#define PELCO_AF_FRAME_LEN 18
void pelco_af_frame(uint8_t out[PELCO_AF_FRAME_LEN]);

#endif

general/package/anjvision-mcl18d/src/pelco.c

new, 199 lines. Pelco-D frames, coordinate mapping and the keep-alive frame: pure functions, no I/O.

#include "pelco.h"

#include <math.h>

void pelco_frame(uint8_t out[PELCO_FRAME_LEN], uint8_t addr, uint8_t c1,
                 uint8_t c2, uint8_t d1, uint8_t d2) {
    out[0] = PELCO_SYNC;
    out[1] = addr;
    out[2] = c1;
    out[3] = c2;
    out[4] = d1;
    out[5] = d2;
    out[6] = (uint8_t)(addr + c1 + c2 + d1 + d2);
}

uint8_t pelco_speed(double v) {
    if (!(v > 0.0)) {  // also catches NaN
        return 0;
    }
    if (v >= 1.0) {
        return PELCO_SPEED_MAX;
    }
    long s = lround(v * PELCO_SPEED_MAX);
    return (uint8_t)(s < 1 ? 1 : s);
}

void pelco_motion_frame(uint8_t out[PELCO_FRAME_LEN], uint8_t addr,
                        const PelcoMotion *m, const PelcoGeom *g) {
    uint8_t c1 = 0, c2 = 0, d1 = 0, d2 = 0;
    int pan = g->pan_invert ? -m->pan : m->pan;
    int tilt = g->tilt_invert ? -m->tilt : m->tilt;

    if (pan > 0) {
        c2 |= PELCO_RIGHT;
    } else if (pan < 0) {
        c2 |= PELCO_LEFT;
    }
    if (pan) {
        d1 = m->pan_speed;
    }
    if (tilt > 0) {
        c2 |= PELCO_UP;
    } else if (tilt < 0) {
        c2 |= PELCO_DOWN;
    }
    if (tilt) {
        d2 = m->tilt_speed;
    }
    if (m->zoom > 0) {
        c2 |= PELCO_TELE;
    } else if (m->zoom < 0) {
        c2 |= PELCO_WIDE;
    }
    if (m->focus > 0) {
        c2 |= PELCO_FOCUS_FAR;
    } else if (m->focus < 0) {
        c1 |= PELCO_FOCUS_NEAR;
    }
    if (m->iris > 0) {
        c1 |= PELCO_IRIS_OPEN;
    } else if (m->iris < 0) {
        c1 |= PELCO_IRIS_CLOSE;
    }
    if (!pan && !tilt && (m->zoom || m->focus || m->iris)) {
        d1 = d2 = m->zoom && m->zoom_speed ? m->zoom_speed : PELCO_LENS_SPEED;
    }
    pelco_frame(out, addr, c1, c2, d1, d2);
}

void pelco_state_move(PelcoMoveState *s, enum PelcoAxis axis, int dir,
                      uint8_t speed, long long now_ms) {
    int *dirs[PELCO_AXES] = {&s->m.pan, &s->m.tilt, &s->m.zoom, &s->m.focus, &s->m.iris};

    for (int a = 0; a < PELCO_AXES; a++) {
        if (now_ms - s->ms[a] > PELCO_COMBINE_MS) {
            *dirs[a] = 0;
        }
    }
    *dirs[axis] = dir;
    s->ms[axis] = now_ms;
    if (axis == PELCO_AXIS_PAN) {
        s->m.pan_speed = speed;
    } else if (axis == PELCO_AXIS_TILT) {
        s->m.tilt_speed = speed;
    } else if (axis == PELCO_AXIS_ZOOM) {
        s->m.zoom_speed = speed;
    }
}

bool pelco_state_moving(const PelcoMoveState *s) {
    return s->m.pan || s->m.tilt || s->m.zoom || s->m.focus || s->m.iris;
}

static double clamp(double v, double lo, double hi) {
    return v < lo ? lo : v > hi ? hi : v;
}

// Degrees to hundredths in 0..35999, wrapping.
static uint16_t hundredths(double deg) {
    deg = fmod(deg, 360.0);
    if (deg < 0.0) {
        deg += 360.0;
    }
    long v = lround(deg * 100.0);
    return (uint16_t)(v >= 36000 ? v - 36000 : v);
}

// Hundredths to degrees in -180..+180.
static double signed_degrees(uint16_t v) {
    double deg = (v % 36000) / 100.0;
    return deg > 180.0 ? deg - 360.0 : deg;
}

uint16_t pelco_pan_value(double x, const PelcoGeom *g) {
    double deg = x * 180.0;
    return hundredths(g->pan_invert ? -deg : deg);
}

double pelco_pan_generic(uint16_t v, const PelcoGeom *g) {
    double deg = signed_degrees(v);
    return (g->pan_invert ? -deg : deg) / 180.0;
}

// Pelco-D counts tilt from the horizon downwards: 0 level, 9000 straight down,
// and above the horizon as 36000 less the angle. Up is positive here.
uint16_t pelco_tilt_value(double y, const PelcoGeom *g) {
    double up = clamp(y * 90.0, g->tilt_min, g->tilt_max);
    if (g->tilt_invert) {
        up = -up;
    }
    return hundredths(-up);
}

double pelco_tilt_generic(uint16_t v, const PelcoGeom *g) {
    double up = -signed_degrees(v);
    if (g->tilt_invert) {
        up = -up;
    }
    return clamp(up / 90.0, -1.0, 1.0);
}

uint16_t pelco_zoom_value(double z) {
    return (uint16_t)lround(clamp(z, 0.0, 1.0) * 65535.0);
}

double pelco_zoom_generic(uint16_t v) { return v / 65535.0; }

double pelco_pan_add(double x, double dx) {
    double r = fmod(x + dx + 1.0, 2.0);
    if (r < 0.0) {
        r += 2.0;
    }
    return r - 1.0;
}

double pelco_tilt_add(double y, double dy, const PelcoGeom *g) {
    return clamp(y + dy, g->tilt_min / 90.0, g->tilt_max / 90.0);
}

double pelco_zoom_add(double z, double dz) { return clamp(z + dz, 0.0, 1.0); }

void pelco_value_frame(uint8_t out[PELCO_FRAME_LEN], uint8_t addr, uint8_t op,
                       uint16_t value) {
    pelco_frame(out, addr, 0, op, (uint8_t)(value >> 8), (uint8_t)value);
}

bool pelco_find_reply(const uint8_t *buf, int n, uint8_t addr, uint8_t reply_op,
                      uint16_t *value) {
    for (int i = 0; i + PELCO_FRAME_LEN <= n; i++) {
        const uint8_t *f = buf + i;
        if (f[0] != PELCO_SYNC || f[1] != addr || f[2] != 0 || f[3] != reply_op) {
            continue;
        }
        if ((uint8_t)(f[1] + f[2] + f[3] + f[4] + f[5]) != f[6]) {
            continue;
        }
        *value = (uint16_t)(f[4] << 8 | f[5]);
        return true;
    }
    return false;
}

void pelco_af_frame(uint8_t out[PELCO_AF_FRAME_LEN]) {
    static const uint8_t body[PELCO_AF_FRAME_LEN - 1] = {
        0x51, 0x01, 0x04, 0x78, 0x01, 0x11,  // header
        0x12, 0x34, 0x08, 0x00,              // focus values, whole frame and centre
        0x01,                                // total gain
        0x30,                                // 2560-wide main stream, day
        0x12, 0x34,                          // raw centre statistic
        0x00, 0x00, 0x00,                    // IR-cut mode, IR lamp %, white lamp %
    };
    uint8_t sum = 0;

    for (int i = 0; i < PELCO_AF_FRAME_LEN - 1; i++) {
        out[i] = body[i];
        sum += body[i];
    }
    out[PELCO_AF_FRAME_LEN - 1] = sum;
}

general/package/anjvision-mcl18d/src/main.c

new, 666 lines. pelco-ptz: command line, serial port, locking, state, presets, keep-alive.

// pelco-ptz: drive a Pelco-D pan/tilt/zoom head, or the MC-L18D's lens board,
// on a serial port, one command per run, for onvif_simple_server's PTZ hooks
// (/etc/onvif.conf) and mcl18d-af.
//
//   pelco-ptz move left|right|up|down|in|out [SPEED]   continuous, SPEED 0..1
//   pelco-ptz focus near|far     manual focus, until stop
//   pelco-ptz iris open|close    until stop
//   pelco-ptz stop
//   pelco-ptz abs X Y Z          absolute, generic space; "nan" leaves an axis
//   pelco-ptz rel DX DY DZ       relative, same scale
//   pelco-ptz position           prints "x,y,z"
//   pelco-ptz moving             prints 1 or 0
//   pelco-ptz home | sethome
//   pelco-ptz preset list | set NAME | goto N | remove N
//   pelco-ptz keepalive          wake the lens board and keep it awake, forever
//
// The generic space is described in pelco.h. Every run takes an exclusive lock
// so two requests never interleave frames on the wire. Position comes from the
// head's own replies to the Pelco-D position queries; a head that does not
// answer them gets the last position this tool commanded instead.

#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <syslog.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

#include "pelco.h"

// Overridable at build time so the host test can run without /etc and /tmp.
#ifndef CONF_FILE
#define CONF_FILE "/etc/pelco-ptz.conf"
#endif
#ifndef PRESET_FILE
#define PRESET_FILE "/etc/pelco-ptz.presets"
#endif
#ifndef STATE_FILE
#define STATE_FILE "/tmp/pelco-ptz.state"
#endif
#ifndef LOCK_FILE
#define LOCK_FILE "/tmp/pelco-ptz.lock"
#endif
#define PRESET_FIRST 2   // 1 is the home position
#define NAME_MAX_LEN 64

static struct {
    char port[96];
    int baud;
    int address;
    PelcoGeom geom;
    int home_preset;
    int max_preset;
    int settle_ms;
    int query_timeout_ms;
    int keepalive_ms;
} conf = {
    .port = "/dev/ttyS2",
    .baud = 57600,
    .address = 1,
    .geom = {false, false, -90.0, 90.0},
    .home_preset = 1,
    .max_preset = 32,
    .settle_ms = 3000,
    .query_timeout_ms = 300,
    .keepalive_ms = 100,
};

// What this tool last did, kept across runs.
static struct {
    PelcoMoveState move;
    double x, y, z;            // last known position, generic space
    long long busy_until_ms;   // an absolute move or preset is still travelling
} st = {.x = 0.0, .y = 0.0, .z = 0.0};

static int port_fd = -1;

// Adding +0.0 turns a negative zero into a positive one, so "-0.0000" never
// reaches an ONVIF client or the preset file.
static double nz(double v) { return v + 0.0; }

static long long now_ms(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

static void load_conf(void) {
    FILE *f = fopen(CONF_FILE, "r");
    char line[160], key[64], val[96];
    if (!f) {
        return;
    }
    while (fgets(line, sizeof line, f)) {
        if (line[0] == '#' || sscanf(line, " %63[^= ] = %95s", key, val) != 2) {
            continue;
        }
        if (!strcmp(key, "port")) {
            snprintf(conf.port, sizeof conf.port, "%s", val);
        } else if (!strcmp(key, "baud")) {
            conf.baud = atoi(val);
        } else if (!strcmp(key, "address")) {
            conf.address = atoi(val);
        } else if (!strcmp(key, "pan_invert")) {
            conf.geom.pan_invert = atoi(val) != 0;
        } else if (!strcmp(key, "tilt_invert")) {
            conf.geom.tilt_invert = atoi(val) != 0;
        } else if (!strcmp(key, "tilt_min")) {
            conf.geom.tilt_min = atof(val);
        } else if (!strcmp(key, "tilt_max")) {
            conf.geom.tilt_max = atof(val);
        } else if (!strcmp(key, "home_preset")) {
            conf.home_preset = atoi(val);
        } else if (!strcmp(key, "max_preset")) {
            conf.max_preset = atoi(val);
        } else if (!strcmp(key, "settle_ms")) {
            conf.settle_ms = atoi(val);
        } else if (!strcmp(key, "query_timeout_ms")) {
            conf.query_timeout_ms = atoi(val);
        } else if (!strcmp(key, "keepalive_ms")) {
            conf.keepalive_ms = atoi(val);
        }
    }
    fclose(f);
    if (conf.address < 0 || conf.address > 255) {
        syslog(LOG_WARNING, "PTZ_CONF_ADDRESS %d is not 0..255, using 1", conf.address);
        conf.address = 1;
    }
    if (conf.max_preset > 255) {
        conf.max_preset = 255;
    }
}

static void load_state(void) {
    FILE *f = fopen(STATE_FILE, "r");
    if (!f) {
        return;
    }
    PelcoMoveState *m = &st.move;
    int ps, ts, zs;
    if (fscanf(f, "%d %d %lld %d %d %lld %d %d %lld %d %lld %d %lld %lf %lf %lf %lld",
               &m->m.pan, &ps, &m->ms[PELCO_AXIS_PAN], &m->m.tilt, &ts,
               &m->ms[PELCO_AXIS_TILT], &m->m.zoom, &zs, &m->ms[PELCO_AXIS_ZOOM],
               &m->m.focus, &m->ms[PELCO_AXIS_FOCUS], &m->m.iris, &m->ms[PELCO_AXIS_IRIS],
               &st.x, &st.y, &st.z, &st.busy_until_ms) == 17) {
        m->m.pan_speed = (uint8_t)ps;
        m->m.tilt_speed = (uint8_t)ts;
        m->m.zoom_speed = (uint8_t)zs;
    } else {
        memset(&st, 0, sizeof st);
    }
    fclose(f);
}

static void save_state(void) {
    FILE *f = fopen(STATE_FILE ".tmp", "w");
    if (!f) {
        return;
    }
    const PelcoMoveState *m = &st.move;
    fprintf(f, "%d %d %lld %d %d %lld %d %d %lld %d %lld %d %lld %.6f %.6f %.6f %lld\n",
            m->m.pan, m->m.pan_speed, m->ms[PELCO_AXIS_PAN], m->m.tilt, m->m.tilt_speed,
            m->ms[PELCO_AXIS_TILT], m->m.zoom, m->m.zoom_speed, m->ms[PELCO_AXIS_ZOOM],
            m->m.focus, m->ms[PELCO_AXIS_FOCUS], m->m.iris, m->ms[PELCO_AXIS_IRIS],
            st.x, st.y, st.z, st.busy_until_ms);
    fclose(f);
    rename(STATE_FILE ".tmp", STATE_FILE);
}

static speed_t baud_const(int baud) {
    switch (baud) {
    case 1200: return B1200;
    case 2400: return B2400;
    case 4800: return B4800;
    case 9600: return B9600;
    case 19200: return B19200;
    case 38400: return B38400;
    case 57600: return B57600;
    case 115200: return B115200;
    default: return 0;
    }
}

static int open_port(void) {
    struct termios tio;
    speed_t sp = baud_const(conf.baud);

    if (!sp) {
        syslog(LOG_ERR, "PTZ_CONF_BAUD %d is not a rate the port can be set to", conf.baud);
        return -1;
    }
    port_fd = open(conf.port, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (port_fd < 0) {
        syslog(LOG_ERR, "PTZ_PORT_OPEN_FAILED %s: %s", conf.port, strerror(errno));
        return -1;
    }
    if (tcgetattr(port_fd, &tio) != 0) {
        syslog(LOG_ERR, "PTZ_PORT_SETUP_FAILED %s: %s", conf.port, strerror(errno));
        return -1;
    }
    cfmakeraw(&tio);
    tio.c_cflag |= CLOCAL | CREAD;
    tio.c_cflag &= ~(CSTOPB | PARENB | CRTSCTS);
    cfsetispeed(&tio, sp);
    cfsetospeed(&tio, sp);
    if (tcsetattr(port_fd, TCSANOW, &tio) != 0) {
        syslog(LOG_ERR, "PTZ_PORT_SETUP_FAILED %s: %s", conf.port, strerror(errno));
        return -1;
    }
    return 0;
}

static int send_frame(const uint8_t f[PELCO_FRAME_LEN]) {
    ssize_t n = write(port_fd, f, PELCO_FRAME_LEN);
    if (n != PELCO_FRAME_LEN) {
        syslog(LOG_ERR, "PTZ_WRITE_FAILED %s: %s", conf.port,
               n < 0 ? strerror(errno) : "short write");
        return -1;
    }
    tcdrain(port_fd);
    return 0;
}

// Ask for one axis's absolute position. False when the head does not answer.
static bool query(uint8_t op, uint8_t reply, uint16_t *value) {
    uint8_t f[PELCO_FRAME_LEN], buf[64];
    int n = 0;
    long long deadline;

    tcflush(port_fd, TCIFLUSH);
    pelco_value_frame(f, (uint8_t)conf.address, op, 0);
    if (send_frame(f) != 0) {
        return false;
    }
    deadline = now_ms() + conf.query_timeout_ms;
    while (n < (int)sizeof buf) {
        long long left = deadline - now_ms();
        struct pollfd p = {.fd = port_fd, .events = POLLIN};
        if (left <= 0 || poll(&p, 1, (int)left) <= 0) {
            break;
        }
        ssize_t r = read(port_fd, buf + n, sizeof buf - n);
        if (r <= 0) {
            break;
        }
        n += (int)r;
        if (pelco_find_reply(buf, n, (uint8_t)conf.address, reply, value)) {
            return true;
        }
    }
    return false;
}

// Refresh st.x/y/z from the head where it answers.
static void read_position(void) {
    uint16_t v;
    if (query(PELCO_QUERY_PAN, PELCO_REPLY_PAN, &v)) {
        st.x = pelco_pan_generic(v, &conf.geom);
    }
    if (query(PELCO_QUERY_TILT, PELCO_REPLY_TILT, &v)) {
        st.y = pelco_tilt_generic(v, &conf.geom);
    }
    if (query(PELCO_QUERY_ZOOM, PELCO_REPLY_ZOOM, &v)) {
        st.z = pelco_zoom_generic(v);
    }
}

static int send_motion(void) {
    uint8_t f[PELCO_FRAME_LEN];
    pelco_motion_frame(f, (uint8_t)conf.address, &st.move.m, &conf.geom);
    return send_frame(f);
}

static void stop_motion_state(void) {
    memset(&st.move.m, 0, sizeof st.move.m);
}

static int cmd_move(const char *dir, const char *speed_arg) {
    double v = speed_arg ? atof(speed_arg) : 0.5;
    uint8_t speed = pelco_speed(v);
    enum PelcoAxis axis;
    int d;

    if (!strcmp(dir, "left")) {
        axis = PELCO_AXIS_PAN, d = -1;
    } else if (!strcmp(dir, "right")) {
        axis = PELCO_AXIS_PAN, d = 1;
    } else if (!strcmp(dir, "up")) {
        axis = PELCO_AXIS_TILT, d = 1;
    } else if (!strcmp(dir, "down")) {
        axis = PELCO_AXIS_TILT, d = -1;
    } else if (!strcmp(dir, "in")) {
        axis = PELCO_AXIS_ZOOM, d = 1;
    } else if (!strcmp(dir, "out")) {
        axis = PELCO_AXIS_ZOOM, d = -1;
    } else if (!strcmp(dir, "far")) {
        axis = PELCO_AXIS_FOCUS, d = 1;
    } else if (!strcmp(dir, "near")) {
        axis = PELCO_AXIS_FOCUS, d = -1;
    } else if (!strcmp(dir, "open")) {
        axis = PELCO_AXIS_IRIS, d = 1;
    } else if (!strcmp(dir, "close")) {
        axis = PELCO_AXIS_IRIS, d = -1;
    } else {
        fprintf(stderr, "unknown direction: %s\n", dir);
        return 1;
    }
    if ((axis == PELCO_AXIS_PAN || axis == PELCO_AXIS_TILT) && speed == 0) {
        d = 0;
    }
    pelco_state_move(&st.move, axis, d, speed, now_ms());
    st.busy_until_ms = 0;
    return send_motion() ? 2 : 0;
}

static int cmd_stop(void) {
    stop_motion_state();
    st.busy_until_ms = 0;
    return send_motion() ? 2 : 0;
}

static bool parse_num(const char *s, double *out) {
    char *end;
    *out = strtod(s, &end);
    return end != s && *end == '\0';
}

// Move to x/y/z; NaN leaves an axis where it is.
static int go_abs(double x, double y, double z) {
    uint8_t f[PELCO_FRAME_LEN];
    uint8_t a = (uint8_t)conf.address;
    int rc = 0;

    stop_motion_state();
    if (!isnan(x)) {
        pelco_value_frame(f, a, PELCO_SET_PAN, pelco_pan_value(x, &conf.geom));
        rc |= send_frame(f);
        st.x = x;
    }
    if (!isnan(y)) {
        pelco_value_frame(f, a, PELCO_SET_TILT, pelco_tilt_value(y, &conf.geom));
        rc |= send_frame(f);
        st.y = pelco_tilt_add(y, 0.0, &conf.geom);
    }
    if (!isnan(z)) {
        pelco_value_frame(f, a, PELCO_SET_ZOOM, pelco_zoom_value(z));
        rc |= send_frame(f);
        st.z = pelco_zoom_add(z, 0.0);
    }
    st.busy_until_ms = now_ms() + conf.settle_ms;
    syslog(LOG_INFO, "PTZ_ABSOLUTE x=%.4f y=%.4f z=%.4f", x, y, z);
    return rc ? 2 : 0;
}

static int cmd_abs(char **argv) {
    double v[3];
    for (int i = 0; i < 3; i++) {
        if (!parse_num(argv[i], &v[i])) {
            fprintf(stderr, "not a number: %s\n", argv[i]);
            return 1;
        }
    }
    return go_abs(v[0], v[1], v[2]);
}

static int cmd_rel(char **argv) {
    double d[3];
    for (int i = 0; i < 3; i++) {
        if (!parse_num(argv[i], &d[i])) {
            fprintf(stderr, "not a number: %s\n", argv[i]);
            return 1;
        }
        if (isnan(d[i])) {
            d[i] = 0.0;
        }
    }
    read_position();
    return go_abs(d[0] != 0.0 ? pelco_pan_add(st.x, d[0]) : NAN,
                  d[1] != 0.0 ? pelco_tilt_add(st.y, d[1], &conf.geom) : NAN,
                  d[2] != 0.0 ? pelco_zoom_add(st.z, d[2]) : NAN);
}

static int cmd_position(void) {
    read_position();
    printf("%.4f,%.4f,%.4f\n", nz(st.x), nz(st.y), nz(st.z));
    return 0;
}

static int cmd_moving(void) {
    printf("%d\n", pelco_state_moving(&st.move) || now_ms() < st.busy_until_ms);
    return 0;
}

static int preset_op(uint8_t op, int n) {
    uint8_t f[PELCO_FRAME_LEN];
    pelco_frame(f, (uint8_t)conf.address, 0, op, 0, (uint8_t)n);
    return send_frame(f);
}

// The preset file: "N=name,x,y,z" per line, which is also what
// onvif_simple_server's get_presets reads.
typedef struct {
    int n;
    char name[NAME_MAX_LEN + 1];
    double x, y, z;
} Preset;

static int load_presets(Preset *p, int max) {
    FILE *f = fopen(PRESET_FILE, "r");
    char line[160];
    int count = 0;
    if (!f) {
        return 0;
    }
    while (count < max && fgets(line, sizeof line, f)) {
        Preset *q = &p[count];
        if (sscanf(line, "%d=%64[^,],%lf,%lf,%lf", &q->n, q->name, &q->x, &q->y, &q->z) == 5) {
            count++;
        }
    }
    fclose(f);
    return count;
}

static int save_presets(const Preset *p, int count) {
    FILE *f = fopen(PRESET_FILE ".tmp", "w");
    if (!f) {
        syslog(LOG_ERR, "PTZ_PRESET_SAVE_FAILED %s: %s", PRESET_FILE, strerror(errno));
        return -1;
    }
    for (int i = 0; i < count; i++) {
        fprintf(f, "%d=%s,%.4f,%.4f,%.4f\n", p[i].n, p[i].name, nz(p[i].x), nz(p[i].y), nz(p[i].z));
    }
    fclose(f);
    return rename(PRESET_FILE ".tmp", PRESET_FILE);
}

static bool name_ok(const char *s) {
    size_t len = strlen(s);
    if (len == 0 || len > NAME_MAX_LEN) {
        return false;
    }
    for (; *s; s++) {
        if (*s <= ' ' || *s == ',' || *s == '=' || *s == 0x7f) {
            return false;
        }
    }
    return true;
}

static int cmd_preset(int argc, char **argv) {
    Preset p[256];
    int count = load_presets(p, 256);

    if (argc >= 1 && !strcmp(argv[0], "list")) {
        for (int i = 0; i < count; i++) {
            printf("%d=%s,%.4f,%.4f,%.4f\n", p[i].n, p[i].name, nz(p[i].x), nz(p[i].y), nz(p[i].z));
        }
        return 0;
    }
    if (argc < 2) {
        return 1;
    }
    if (!strcmp(argv[0], "set")) {
        int n;
        if (!name_ok(argv[1])) {
            fprintf(stderr, "bad preset name\n");
            return 1;
        }
        for (n = PRESET_FIRST; n <= conf.max_preset; n++) {
            int used = 0;
            for (int i = 0; i < count; i++) {
                used |= p[i].n == n;
            }
            if (!used && n != conf.home_preset) {
                break;
            }
        }
        if (n > conf.max_preset) {
            syslog(LOG_WARNING, "PTZ_PRESET_FULL no free preset in %d..%d", PRESET_FIRST, conf.max_preset);
            return 2;
        }
        read_position();
        if (preset_op(PELCO_SET_PRESET, n) != 0) {
            return 2;
        }
        p[count].n = n;
        snprintf(p[count].name, sizeof p[count].name, "%s", argv[1]);
        p[count].x = st.x;
        p[count].y = st.y;
        p[count].z = st.z;
        syslog(LOG_INFO, "PTZ_PRESET_SET %d %s", n, argv[1]);
        return save_presets(p, count + 1) ? 2 : 0;
    }
    int n = atoi(argv[1]);
    if (n < 1 || n > 255) {
        return 1;
    }
    if (!strcmp(argv[0], "goto")) {
        if (preset_op(PELCO_GOTO_PRESET, n) != 0) {
            return 2;
        }
        stop_motion_state();
        for (int i = 0; i < count; i++) {
            if (p[i].n == n) {
                st.x = p[i].x, st.y = p[i].y, st.z = p[i].z;
            }
        }
        st.busy_until_ms = now_ms() + conf.settle_ms;
        return 0;
    }
    if (!strcmp(argv[0], "remove")) {
        int out = 0;
        if (preset_op(PELCO_CLEAR_PRESET, n) != 0) {
            return 2;
        }
        for (int i = 0; i < count; i++) {
            if (p[i].n != n) {
                p[out++] = p[i];
            }
        }
        syslog(LOG_INFO, "PTZ_PRESET_REMOVED %d", n);
        return save_presets(p, out) ? 2 : 0;
    }
    return 1;
}

static int cmd_home(bool set) {
    if (set) {
        syslog(LOG_INFO, "PTZ_HOME_SET preset %d", conf.home_preset);
        return preset_op(PELCO_SET_PRESET, conf.home_preset) ? 2 : 0;
    }
    stop_motion_state();
    st.busy_until_ms = now_ms() + conf.settle_ms;
    return preset_op(PELCO_GOTO_PRESET, conf.home_preset) ? 2 : 0;
}

// The MC-L18D's lens board drops every Pelco-D frame, for the pan/tilt it
// drives as well as for the lens, unless it has seen autofocus data recently.
// The vendor firmware never lets it doze: it streams a frame per video frame.
// On the camera, 2026-10-28: five frames 33 ms apart woke it, one did not; it
// still obeyed 3 s after the last frame and had gone back to sleep after 40 s;
// a frame every 100 ms kept it awake. So one frame every keepalive_ms, until
// killed. It takes no lock, so commands go out between its frames: each
// write() reaches the tty whole, under the tty's own write lock, and the port
// is blocking here so a write is never cut short.
static int cmd_keepalive(void) {
    uint8_t f[PELCO_AF_FRAME_LEN];
    bool failing = false;

    if (conf.keepalive_ms <= 0) {
        syslog(LOG_INFO, "PTZ_KEEPALIVE_OFF keepalive_ms is %d", conf.keepalive_ms);
        return 0;
    }
    pelco_af_frame(f);
    syslog(LOG_INFO, "PTZ_KEEPALIVE_START %s every %d ms", conf.port, conf.keepalive_ms);
    for (;;) {
        if (port_fd < 0) {
            if (open_port() != 0 ||
                fcntl(port_fd, F_SETFL, fcntl(port_fd, F_GETFL) & ~O_NONBLOCK) != 0) {
                if (port_fd >= 0) {
                    close(port_fd);
                    port_fd = -1;
                }
                sleep(5);
                continue;
            }
        }
        if (write(port_fd, f, sizeof f) != (ssize_t)sizeof f) {
            if (!failing) {
                syslog(LOG_ERR, "PTZ_KEEPALIVE_WRITE_FAILED %s: %s", conf.port, strerror(errno));
            }
            failing = true;
            close(port_fd);
            port_fd = -1;
            sleep(5);
            continue;
        }
        if (failing) {
            syslog(LOG_INFO, "PTZ_KEEPALIVE_RESUMED %s", conf.port);
            failing = false;
        }
        usleep((useconds_t)conf.keepalive_ms * 1000);
    }
}

static void usage(void) {
    fprintf(stderr,
            "usage: pelco-ptz move left|right|up|down|in|out [SPEED]\n"
            "       pelco-ptz focus near|far | iris open|close   (until stop)\n"
            "       pelco-ptz stop | position | moving | home | sethome\n"
            "       pelco-ptz abs X Y Z | rel DX DY DZ   (nan leaves an axis)\n"
            "       pelco-ptz preset list | set NAME | goto N | remove N\n"
            "       pelco-ptz keepalive   (runs until killed)\n");
}

int main(int argc, char **argv) {
    int lock, rc;

    if (argc < 2) {
        usage();
        return 1;
    }
    openlog("pelco-ptz", LOG_PID, LOG_USER);
    load_conf();

    // It runs for as long as the camera does, so it must not hold the lock
    // every other request waits on.
    if (!strcmp(argv[1], "keepalive")) {
        return cmd_keepalive();
    }

    lock = open(LOCK_FILE, O_RDWR | O_CREAT, 0600);
    if (lock < 0 || flock(lock, LOCK_EX) != 0) {
        syslog(LOG_ERR, "PTZ_LOCK_FAILED %s: %s", LOCK_FILE, strerror(errno));
        return 2;
    }
    load_state();

    // Listing presets and reporting motion need no port.
    if (!strcmp(argv[1], "moving")) {
        return cmd_moving();
    }
    if (!strcmp(argv[1], "preset") && argc >= 3 && !strcmp(argv[2], "list")) {
        return cmd_preset(argc - 2, argv + 2);
    }
    if (open_port() != 0) {
        return 2;
    }

    if (!strcmp(argv[1], "move") && argc >= 3) {
        rc = cmd_move(argv[2], argc >= 4 ? argv[3] : NULL);
    } else if (!strcmp(argv[1], "focus") && argc >= 3 &&
               (!strcmp(argv[2], "near") || !strcmp(argv[2], "far"))) {
        rc = cmd_move(argv[2], NULL);
    } else if (!strcmp(argv[1], "iris") && argc >= 3 &&
               (!strcmp(argv[2], "open") || !strcmp(argv[2], "close"))) {
        rc = cmd_move(argv[2], NULL);
    } else if (!strcmp(argv[1], "stop")) {
        rc = cmd_stop();
    } else if (!strcmp(argv[1], "abs") && argc >= 5) {
        rc = cmd_abs(argv + 2);
    } else if (!strcmp(argv[1], "rel") && argc >= 5) {
        rc = cmd_rel(argv + 2);
    } else if (!strcmp(argv[1], "position")) {
        rc = cmd_position();
    } else if (!strcmp(argv[1], "home")) {
        rc = cmd_home(false);
    } else if (!strcmp(argv[1], "sethome")) {
        rc = cmd_home(true);
    } else if (!strcmp(argv[1], "preset") && argc >= 3) {
        rc = cmd_preset(argc - 2, argv + 2);
    } else {
        usage();
        rc = 1;
    }
    save_state();
    close(port_fd);
    return rc;
}

general/package/anjvision-mcl18d/src/Makefile

new, 39 lines. Builds pelco-ptz; test, e2e and af targets run the host tests.

CFLAGS ?= -Os
CFLAGS += -Wall -Wextra

all: pelco-ptz

pelco-ptz: main.c pelco.c pelco.h
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ main.c pelco.c -lm

# Host-native: the frames and the coordinate mapping, byte for byte.
test: tests/pelco_test.c pelco.c pelco.h
	$(CC) -Wall -Wextra -I. -o pelco_test tests/pelco_test.c pelco.c -lm
	./pelco_test

# Host-native: the real binary against a simulated Pelco-D head on a pty.
# tests/onvif_e2e.py runs the same through onvif_simple_server; see its header.
E2E_DIR ?= /tmp/pelco-ptz-e2e
e2e: main.c pelco.c pelco.h
	mkdir -p $(E2E_DIR)
	$(CC) -Wall -Wextra -DCONF_FILE='"$(E2E_DIR)/conf"' -DPRESET_FILE='"$(E2E_DIR)/presets"' \
		-DSTATE_FILE='"$(E2E_DIR)/state"' -DLOCK_FILE='"$(E2E_DIR)/lock"' \
		-o $(E2E_DIR)/pelco-ptz main.c pelco.c -lm
	python3 tests/pelco_e2e.py $(E2E_DIR)/pelco-ptz $(E2E_DIR)

clean:
	rm -f pelco-ptz pelco_test

# Host-native: mcl18d-af, comment-stripped as it ships, against a simulated
# lens under busybox ash. BUSYBOX is a host build of the tree's busybox
# (output/build/busybox-*, built with the host compiler).
af: ../files/mcl18d-af tests/af_sim.py
	@test -x "$(BUSYBOX)" || { echo "set BUSYBOX=/path/to/host/busybox"; exit 1; }
	mkdir -p $(E2E_DIR)/af/sh
	ln -sf $(abspath $(BUSYBOX)) $(E2E_DIR)/af/sh/busybox
	printf '#!/bin/sh\nexec %s ash "$$@"\n' $(E2E_DIR)/af/sh/busybox > $(E2E_DIR)/af/sh/ash
	chmod +x $(E2E_DIR)/af/sh/ash
	awk -f ../../../scripts/strip-shell-comments.awk ../files/mcl18d-af > $(E2E_DIR)/af/mcl18d-af
	python3 tests/af_sim.py $(E2E_DIR)/af/sh/ash $(E2E_DIR)/af/mcl18d-af $(E2E_DIR)/af

.PHONY: all test e2e af clean

general/package/anjvision-mcl18d/src/tests/pelco_test.c

new, 250 lines. Unit tests: every frame byte for byte, mapping, reply parsing, the combine rule.

// Host-native checks for pelco.c: every frame byte for byte against the
// Pelco-D protocol's own examples, and the generic-space mapping both ways.
// Build and run with `make test` in src/.

#include <math.h>
#include <stdio.h>
#include <string.h>

#include "pelco.h"

static int failures;

static void expect_frame(const char *what, const uint8_t got[PELCO_FRAME_LEN],
                         const uint8_t want[PELCO_FRAME_LEN]) {
    if (memcmp(got, want, PELCO_FRAME_LEN) != 0) {
        failures++;
        printf("FAIL %s:", what);
        for (int i = 0; i < PELCO_FRAME_LEN; i++) {
            printf(" %02x", got[i]);
        }
        printf("  want");
        for (int i = 0; i < PELCO_FRAME_LEN; i++) {
            printf(" %02x", want[i]);
        }
        printf("\n");
    }
}

static void expect_int(const char *what, long got, long want) {
    if (got != want) {
        failures++;
        printf("FAIL %s: %ld, want %ld\n", what, got, want);
    }
}

static void expect_near(const char *what, double got, double want) {
    if (fabs(got - want) > 1e-3) {
        failures++;
        printf("FAIL %s: %f, want %f\n", what, got, want);
    }
}

static const PelcoGeom STRAIGHT = {false, false, -90.0, 90.0};

static void test_frames(void) {
    uint8_t f[PELCO_FRAME_LEN];
    PelcoMotion m;

    memset(&m, 0, sizeof m);
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("stop", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01});

    m = (PelcoMotion){.pan = -1, .pan_speed = 0x20};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("left 0x20", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x04, 0x20, 0x00, 0x25});

    m = (PelcoMotion){.tilt = 1, .tilt_speed = 0x20};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("up 0x20", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x08, 0x00, 0x20, 0x29});

    m = (PelcoMotion){.pan = 1, .pan_speed = 0x3f, .tilt = -1, .tilt_speed = 0x10, .zoom = 1};
    pelco_motion_frame(f, 2, &m, &STRAIGHT);
    expect_frame("right+down+tele", f,
                 (const uint8_t[]){0xff, 0x02, 0x00, 0x32, 0x3f, 0x10, 0x83});

    // Lens-only frames carry a speed in both data bytes, as the vendor
    // firmware sends them to the lens board (AF-BOARD-PROTOCOL.md section 1).
    m = (PelcoMotion){.zoom = -1};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("wide, no speed", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x40, 0x30, 0x30, 0xa1});
    m = (PelcoMotion){.zoom = 1, .zoom_speed = 0x1e};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("tele 0x1e", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x20, 0x1e, 0x1e, 0x5d});

    // The vendor's FocusNearAutoOff / FocusFarAutoOff / IrisOpenAutoOff /
    // IrisCloseAutoOff frames, byte for byte.
    m = (PelcoMotion){.focus = -1};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("focus near", f, (const uint8_t[]){0xff, 0x01, 0x01, 0x00, 0x30, 0x30, 0x62});
    m = (PelcoMotion){.focus = 1};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("focus far", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x80, 0x30, 0x30, 0xe1});
    m = (PelcoMotion){.iris = 1};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("iris open", f, (const uint8_t[]){0xff, 0x01, 0x02, 0x00, 0x30, 0x30, 0x63});
    m = (PelcoMotion){.iris = -1};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("iris close", f, (const uint8_t[]){0xff, 0x01, 0x04, 0x00, 0x30, 0x30, 0x65});

    // Pan speed stays in data 1 when the lens moves along with the head.
    m = (PelcoMotion){.pan = 1, .pan_speed = 0x20, .focus = 1};
    pelco_motion_frame(f, 1, &m, &STRAIGHT);
    expect_frame("right+far", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x82, 0x20, 0x00, 0xa3});

    PelcoGeom inv = {true, true, -90.0, 90.0};
    m = (PelcoMotion){.pan = -1, .pan_speed = 0x20, .tilt = 1, .tilt_speed = 0x20};
    pelco_motion_frame(f, 1, &m, &inv);
    expect_frame("inverted left+up", f,
                 (const uint8_t[]){0xff, 0x01, 0x00, 0x12, 0x20, 0x20, 0x53});

    pelco_frame(f, 1, 0, PELCO_SET_PRESET, 0, 1);
    expect_frame("set preset 1", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x03, 0x00, 0x01, 0x05});
    pelco_frame(f, 1, 0, PELCO_CLEAR_PRESET, 0, 1);
    expect_frame("clear preset 1", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x05, 0x00, 0x01, 0x07});
    pelco_frame(f, 1, 0, PELCO_GOTO_PRESET, 0, 1);
    expect_frame("goto preset 1", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x07, 0x00, 0x01, 0x09});

    pelco_value_frame(f, 1, PELCO_QUERY_PAN, 0);
    expect_frame("query pan", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52});
    pelco_value_frame(f, 1, PELCO_SET_PAN, 9000);
    expect_frame("pan to 90.00", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x4b, 0x23, 0x28, 0x97});
    pelco_value_frame(f, 1, PELCO_SET_ZOOM, 0xffff);
    expect_frame("zoom to tele", f, (const uint8_t[]){0xff, 0x01, 0x00, 0x4f, 0xff, 0xff, 0x4e});
}

static void test_speed(void) {
    expect_int("speed 0", pelco_speed(0.0), 0);
    expect_int("speed nan", pelco_speed(NAN), 0);
    expect_int("speed tiny", pelco_speed(0.001), 1);
    expect_int("speed half", pelco_speed(0.5), 32);
    expect_int("speed 1", pelco_speed(1.0), 0x3f);
    expect_int("speed over", pelco_speed(7.0), 0x3f);
}

static void test_mapping(void) {
    PelcoGeom g = STRAIGHT;

    expect_int("pan 0", pelco_pan_value(0.0, &g), 0);
    expect_int("pan +0.5", pelco_pan_value(0.5, &g), 9000);
    expect_int("pan -0.5", pelco_pan_value(-0.5, &g), 27000);
    expect_int("pan +1", pelco_pan_value(1.0, &g), 18000);
    expect_int("pan -1", pelco_pan_value(-1.0, &g), 18000);
    expect_near("pan back 27000", pelco_pan_generic(27000, &g), -0.5);
    expect_near("pan back 9000", pelco_pan_generic(9000, &g), 0.5);

    // Down is positive in Pelco-D, up wraps below 36000.
    expect_int("tilt 30 down", pelco_tilt_value(-30.0 / 90.0, &g), 3000);
    expect_int("tilt 10 up", pelco_tilt_value(10.0 / 90.0, &g), 35000);
    expect_near("tilt back 3000", pelco_tilt_generic(3000, &g), -30.0 / 90.0);
    expect_near("tilt back 35000", pelco_tilt_generic(35000, &g), 10.0 / 90.0);

    PelcoGeom lim = {false, false, -90.0, 0.0};
    expect_int("tilt clamped to horizon", pelco_tilt_value(0.5, &lim), 0);
    expect_near("tilt add clamps", pelco_tilt_add(-0.2, 0.5, &lim), 0.0);

    PelcoGeom inv = {true, true, -90.0, 90.0};
    expect_int("pan inverted", pelco_pan_value(0.5, &inv), 27000);
    expect_near("pan inverted back", pelco_pan_generic(27000, &inv), 0.5);
    expect_int("tilt inverted", pelco_tilt_value(-30.0 / 90.0, &inv), 33000);
    expect_near("tilt inverted back", pelco_tilt_generic(33000, &inv), -30.0 / 90.0);

    expect_int("zoom 0", pelco_zoom_value(0.0), 0);
    expect_int("zoom 1", pelco_zoom_value(1.0), 65535);
    expect_int("zoom over", pelco_zoom_value(2.0), 65535);
    expect_near("zoom back", pelco_zoom_generic(32768), 0.5);

    expect_near("pan add wraps right", pelco_pan_add(0.9, 0.2), -0.9);
    expect_near("pan add wraps left", pelco_pan_add(-0.9, -0.2), 0.9);
    expect_near("zoom add clamps", pelco_zoom_add(0.9, 0.5), 1.0);

    // Every pan value survives the round trip to within a hundredth of a degree.
    for (int v = 0; v < 36000; v += 7) {
        uint16_t back = pelco_pan_value(pelco_pan_generic((uint16_t)v, &g), &g);
        if (back != v) {
            failures++;
            printf("FAIL pan round trip %d -> %d\n", v, back);
            break;
        }
    }
}

static void test_replies(void) {
    uint16_t v = 0;
    const uint8_t noisy[] = {0x00, 0xff, 0x13, 0xff, 0x01, 0x00, 0x59, 0x23, 0x28, 0xa5, 0x7e};
    expect_int("reply found past noise", pelco_find_reply(noisy, sizeof noisy, 1, PELCO_REPLY_PAN, &v), 1);
    expect_int("reply value", v, 9000);

    const uint8_t bad_sum[] = {0xff, 0x01, 0x00, 0x59, 0x23, 0x28, 0xa6};
    expect_int("bad checksum refused", pelco_find_reply(bad_sum, sizeof bad_sum, 1, PELCO_REPLY_PAN, &v), 0);
    const uint8_t other_addr[] = {0xff, 0x02, 0x00, 0x59, 0x23, 0x28, 0xa6};
    expect_int("other address refused", pelco_find_reply(other_addr, sizeof other_addr, 1, PELCO_REPLY_PAN, &v), 0);
    const uint8_t tilt[] = {0xff, 0x01, 0x00, 0x5b, 0x0b, 0xb8, 0x1f};
    expect_int("tilt reply is not a pan reply", pelco_find_reply(tilt, sizeof tilt, 1, PELCO_REPLY_PAN, &v), 0);
    expect_int("tilt reply", pelco_find_reply(tilt, sizeof tilt, 1, PELCO_REPLY_TILT, &v), 1);
    expect_int("tilt value", v, 3000);
}

static void test_combine(void) {
    PelcoMoveState s;
    memset(&s, 0, sizeof s);
    for (int a = 0; a < PELCO_AXES; a++) {
        s.ms[a] = -100000;
    }

    // One diagonal request: right then up, milliseconds apart.
    pelco_state_move(&s, PELCO_AXIS_PAN, 1, 0x20, 1000);
    pelco_state_move(&s, PELCO_AXIS_TILT, 1, 0x10, 1004);
    expect_int("diagonal keeps pan", s.m.pan, 1);
    expect_int("diagonal keeps tilt", s.m.tilt, 1);

    // The next request is tilt only: the old pan is not part of it.
    pelco_state_move(&s, PELCO_AXIS_TILT, -1, 0x10, 1600);
    expect_int("new request drops old pan", s.m.pan, 0);
    expect_int("new request sets tilt", s.m.tilt, -1);
    expect_int("still moving", pelco_state_moving(&s), 1);

    pelco_state_move(&s, PELCO_AXIS_ZOOM, 1, 0, 1700);
    expect_int("zoom keeps the tilt of the same request window", s.m.tilt, -1);
    pelco_state_move(&s, PELCO_AXIS_ZOOM, 1, 0, 2500);
    expect_int("later zoom drops tilt", s.m.tilt, 0);

    pelco_state_move(&s, PELCO_AXIS_FOCUS, -1, 0, 3000);
    expect_int("focus is a new request, zoom stops", s.m.zoom, 0);
    expect_int("focus near", s.m.focus, -1);
    expect_int("focus counts as moving", pelco_state_moving(&s), 1);
    pelco_state_move(&s, PELCO_AXIS_IRIS, 1, 0, 4000);
    expect_int("iris drops focus", s.m.focus, 0);
}

// The keep-alive frame the lens board was seen to wake on, 2026-10-28.
static void test_af_frame(void) {
    static const uint8_t want[PELCO_AF_FRAME_LEN] = {
        0x51, 0x01, 0x04, 0x78, 0x01, 0x11, 0x12, 0x34, 0x08,
        0x00, 0x01, 0x30, 0x12, 0x34, 0x00, 0x00, 0x00, 0xa5,
    };
    uint8_t f[PELCO_AF_FRAME_LEN];

    pelco_af_frame(f);
    for (int i = 0; i < PELCO_AF_FRAME_LEN; i++) {
        if (f[i] != want[i]) {
            failures++;
            printf("FAIL af frame byte %d: %02x, want %02x\n", i, f[i], want[i]);
        }
    }
}

int main(void) {
    test_frames();
    test_af_frame();
    test_speed();
    test_mapping();
    test_replies();
    test_combine();
    if (failures) {
        printf("%d failure(s)\n", failures);
        return 1;
    }
    printf("pelco_test: all passed\n");
    return 0;
}

general/package/anjvision-mcl18d/src/tests/e2e_head.py

new, 75 lines. A simulated Pelco-D head on a pseudo-terminal, shared by the e2e tests.

"""A simulated Pelco-D head on a pseudo-terminal, shared by the e2e tests."""
import os
import pty
import threading
import tty


def frame(op, value=0, c1=0, addr=1):
    """The bytes of one frame, as the tests write them: 'ff 01 00 4b 23 28 97'."""
    f = [0xFF, addr, c1, op, value >> 8, value & 0xFF]
    return " ".join(f"{b:02x}" for b in f + [sum(f[1:]) & 0xFF])


class Head:
    def __init__(self, fd, answers=True):
        self.fd, self.answers = fd, answers
        self.pan = self.tilt = self.zoom = 0
        self.frames, self.buf, self.stop = [], b"", False
        self.af_frames = 0   # whole keep-alive frames (pelco_af_frame) seen
        threading.Thread(target=self.run, daemon=True).start()

    def reply(self, op, v):
        f = bytes([0xFF, 0x01, 0x00, op, v >> 8, v & 0xFF])
        os.write(self.fd, f + bytes([sum(f[1:]) & 0xFF]))

    def run(self):
        while not self.stop:
            try:
                self.buf += os.read(self.fd, 64)
            except OSError:
                return
            while self.buf:
                # A keep-alive frame: 18 bytes from 0x51, the last their sum.
                if self.buf[0] == 0x51:
                    if len(self.buf) < 18:
                        break
                    f, self.buf = self.buf[:18], self.buf[18:]
                    assert sum(f[:17]) & 0xFF == f[17], f"bad keep-alive frame {f.hex()}"
                    self.af_frames += 1
                    continue
                starts = [i for i in (self.buf.find(b"\xff"), self.buf.find(b"\x51")) if i >= 0]
                if not starts:
                    self.buf = b""
                    break
                if min(starts) > 0:
                    self.buf = self.buf[min(starts):]
                    continue
                if len(self.buf) < 7:
                    break
                f, self.buf = self.buf[:7], self.buf[7:]
                assert sum(f[1:6]) & 0xFF == f[6], f"bad checksum {f.hex()}"
                self.frames.append(f.hex(" "))
                op, v = f[3], f[4] << 8 | f[5]
                if op == 0x4B:
                    self.pan = v
                elif op == 0x4D:
                    self.tilt = v
                elif op == 0x4F:
                    self.zoom = v
                elif self.answers and op in (0x51, 0x53, 0x55):
                    self.reply(op + 8, {0x51: self.pan, 0x53: self.tilt, 0x55: self.zoom}[op])


def start(work, answers=True, tilt_max=90):
    master, slave = pty.openpty()
    tty.setraw(master)
    with open(f"{work}/conf", "w") as f:
        f.write(f"port={os.ttyname(slave)}\nbaud=2400\naddress=1\ntilt_min=-90\n"
                f"tilt_max={tilt_max}\nsettle_ms=1500\nquery_timeout_ms=200\n")
    for leftover in ("state", "presets"):
        try:
            os.remove(f"{work}/{leftover}")
        except FileNotFoundError:
            pass
    return Head(master, answers), master, slave

general/package/anjvision-mcl18d/src/tests/pelco_e2e.py

new, 138 lines. The real pelco-ptz binary against the simulated head.

"""End-to-end: run the real pelco-ptz binary against a simulated Pelco-D head
on a pseudo-terminal, and check the frames it sends and what it prints."""
import os
import subprocess
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import e2e_head  # noqa: E402

BIN, WORK = sys.argv[1], sys.argv[2]


failures = 0


def check(what, got, want):
    global failures
    if got != want:
        failures += 1
        print(f"FAIL {what}: {got!r}, want {want!r}")
    else:
        print(f"ok   {what}")


def run(*args):
    r = subprocess.run([BIN, *args], capture_output=True, text=True, timeout=10)
    return r.returncode, r.stdout.strip()


def session(answers):
    return e2e_head.start(WORK, answers, tilt_max=30)


def take(head):
    time.sleep(0.15)
    out, head.frames = head.frames, []
    return out


# --- a head that answers position queries -----------------------------------
head, master, slave = session(answers=True)

check("abs pan/tilt rc", run("abs", "0.5", "-0.333333", "nan")[0], 0)
check("abs frames", take(head), ["ff 01 00 4b 23 28 97", "ff 01 00 4d 0b b8 11"])
check("head pan", head.pan, 9000)
check("head tilt (30 down)", head.tilt, 3000)
check("moving right after abs", run("moving")[1], "1")
check("position from head", run("position")[1], "0.5000,-0.3333,0.0000")
take(head)

check("abs zoom only", run("abs", "nan", "nan", "1")[0], 0)
check("zoom-only frame", take(head), ["ff 01 00 4f ff ff 4e"])

check("abs tilt above limit clamps", run("abs", "0", "0.9", "nan")[0], 0)
check("clamped tilt is 30 up", head.tilt, 33000)
take(head)

run("abs", "0.75", "0", "nan")
take(head)
check("rel pan wraps", run("rel", "0.5", "0", "0")[0], 0)
frames = take(head)
check("rel queried then set pan", [f for f in frames if f.split()[3] in ("4b", "4d", "4f")],
      ["ff 01 00 4b 57 e4 87"])
check("head pan after wrap (-135 = 225 deg)", head.pan, 22500)

check("diagonal right", run("move", "right", "0.5")[0], 0)
check("diagonal up", run("move", "up", "1")[0], 0)
check("diagonal frames", take(head), ["ff 01 00 02 20 00 23", "ff 01 00 0a 20 3f 6a"])
check("moving while driving", run("moving")[1], "1")
time.sleep(0.4)
run("move", "in", "0.5")
check("later zoom request drops pan/tilt", take(head), ["ff 01 00 20 20 20 61"])
time.sleep(0.4)
check("focus near", run("focus", "near")[0], 0)
check("focus near frame (vendor FocusNearAutoOff)", take(head), ["ff 01 01 00 30 30 62"])
check("moving while focusing", run("moving")[1], "1")
time.sleep(0.4)
run("focus", "far")
check("focus far frame (vendor FocusFarAutoOff)", take(head), ["ff 01 00 80 30 30 e1"])
time.sleep(0.4)
run("iris", "open")
check("iris open frame", take(head), ["ff 01 02 00 30 30 63"])
time.sleep(0.4)
run("iris", "close")
check("iris close frame", take(head), ["ff 01 04 00 30 30 65"])
check("focus with no direction refused", run("focus", "in")[0], 1)
check("stop", run("stop")[0], 0)
check("stop frame", take(head), ["ff 01 00 00 00 00 01"])
time.sleep(1.6)
check("idle after settle", run("moving")[1], "0")

check("preset set", run("preset", "set", "door")[0], 0)
check("preset set frame", [f for f in take(head) if f.split()[3] == "03"], ["ff 01 00 03 00 02 06"])
check("preset list", run("preset", "list")[1], "2=door,-0.7500,0.0000,1.0000")
check("bad preset name refused", run("preset", "set", "a,b")[0], 1)
check("preset goto", run("preset", "goto", "2")[0], 0)
check("preset goto frame", take(head), ["ff 01 00 07 00 02 0a"])
check("sethome", run("sethome")[0], 0)
check("home", run("home")[0], 0)
check("home frames", take(head), ["ff 01 00 03 00 01 05", "ff 01 00 07 00 01 09"])
check("preset remove", run("preset", "remove", "2")[0], 0)
check("preset remove frame", take(head), ["ff 01 00 05 00 02 08"])
check("preset list empty", run("preset", "list")[1], "")
head.stop = True
os.close(master)
os.close(slave)

# --- a head that never answers: position comes from what was commanded --------
head, master, slave = session(answers=False)
run("abs", "-0.25", "0.1", "0.5")
take(head)
check("position without replies", run("position")[1], "-0.2500,0.1000,0.5000")
check("unknown verb refused", run("move", "sideways")[0], 1)
head.stop = True

# --- keepalive: whole frames every keepalive_ms, commands still get through ----
head, master, slave = session(answers=False)
with open(f"{WORK}/conf", "a") as f:
    f.write("keepalive_ms=50\n")
ka = subprocess.Popen([BIN, "keepalive"])
time.sleep(1.0)
n = head.af_frames
check(f"keep-alive frames in 1 s at 50 ms ({n})", 12 <= n <= 22, True)
check("move while keepalive runs", run("move", "right", "0.5")[0], 0)
check("stop while keepalive runs", run("stop")[0], 0)
check("command frames whole between keep-alive frames", take(head),
      ["ff 01 00 02 20 00 23", "ff 01 00 00 00 00 01"])
check("keep-alive still running", ka.poll(), None)
ka.terminate()
ka.wait()
with open(f"{WORK}/conf", "a") as f:
    f.write("keepalive_ms=0\n")
check("keepalive_ms=0 exits at once", run("keepalive")[0], 0)
head.stop = True

print(f"{failures} failure(s)" if failures else "e2e: all passed")
sys.exit(1 if failures else 0)

general/package/anjvision-mcl18d/src/tests/onvif_e2e.py

new, 161 lines. ONVIF SOAP requests through the patched server into pelco-ptz and the simulated head.

"""ONVIF end-to-end: SOAP requests into the patched onvif_simple_server (as a
CGI), which runs pelco-ptz, which drives a simulated Pelco-D head on a pty.

    python3 onvif_e2e.py OSS_DIR OSS_BIN PELCO_PTZ WORK

OSS_DIR is onvif_simple_server's source at the onvif-simple-server package's
pinned version with the package's patches applied, built host-native (the
CGI reads its *_files templates relative to it); OSS_BIN is the binary built
there. PELCO_PTZ is a host build from `make e2e` (paths under WORK)."""
import os
import subprocess
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import e2e_head  # noqa: E402
from e2e_head import frame  # noqa: E402

OSS_DIR, OSS_BIN, PTZ_BIN, WORK = sys.argv[1:5]

head, master, slave = e2e_head.start(WORK)
P = PTZ_BIN
conf = f"""model=MC-L18D
manufacturer=OpenIPC
firmware_ver=test
hardware_id=test
serial_num=test
ifs=lo
port=85
scope=onvif://www.onvif.org/Profile/Streaming
name=Profile_0
width=2560
height=1440
url=rtsp://%s/stream=0
snapurl=http://%s/image.jpg
type=H264
ptz=1
min_step_x=-1
max_step_x=1
min_step_y=-1
max_step_y=1
min_step_z=0
max_step_z=1
get_position={P} position
is_moving={P} moving
move_left={P} move left %f
move_right={P} move right %f
move_up={P} move up %f
move_down={P} move down %f
move_in={P} move in %f
move_out={P} move out %f
move_stop={P} stop
move_preset={P} preset goto %d
goto_home_position={P} home
set_preset={P} preset set %s
set_home_position={P} sethome
remove_preset={P} preset remove %d
jump_to_abs={P} abs %f %f %f
jump_to_rel={P} rel %f %f %f
get_presets={P} preset list
"""
with open(f"{WORK}/onvif.conf", "w") as f:
    f.write(conf)

ENV = 'xmlns:s="http://www.w3.org/2003/05/soap-envelope" ' \
      'xmlns:tptz="http://www.onvif.org/ver20/ptz/wsdl" xmlns:tt="http://www.onvif.org/ver10/schema"'


def soap(body):
    req = f'<?xml version="1.0"?><s:Envelope {ENV}><s:Body>{body}</s:Body></s:Envelope>'
    env = dict(os.environ, REQUEST_METHOD="POST", CONTENT_LENGTH=str(len(req)),
               CONTENT_TYPE="application/soap+xml")
    r = subprocess.run([OSS_BIN, "-c", f"{WORK}/onvif.conf", "ptz_service"], input=req,
                       capture_output=True, text=True, cwd=OSS_DIR, env=env, timeout=20)
    return r.stdout


failures = 0


def check(what, cond, detail: object = ""):
    global failures
    if cond:
        print(f"ok   {what}")
    else:
        failures += 1
        print(f"FAIL {what} {detail}")


def take():
    time.sleep(0.2)
    out, head.frames = head.frames, []
    return [f for f in out if f.split()[3] not in ("51", "53", "55")]


PT = '<tptz:ProfileToken>Profile_0</tptz:ProfileToken>'

r = soap(f'<tptz:AbsoluteMove>{PT}<tptz:Position><tt:PanTilt x="0.5" y="-0.333333"/>'
         f'<tt:Zoom x="0.25"/></tptz:Position></tptz:AbsoluteMove>')
check("AbsoluteMove pan/tilt/zoom answered", "AbsoluteMoveResponse" in r, r[-300:])
f = take()
check("AbsoluteMove sets all three", f == [frame(0x4B, 9000), frame(0x4D, 3000), frame(0x4F, 16384)], f)

r = soap(f'<tptz:AbsoluteMove>{PT}<tptz:Position><tt:PanTilt x="-0.5" y="0"/></tptz:Position></tptz:AbsoluteMove>')
f = take()
check("AbsoluteMove pan/tilt leaves zoom alone", f == [frame(0x4B, 27000), frame(0x4D, 0)], f)
check("zoom unchanged on the head", head.zoom == 0x4000, head.zoom)

r = soap(f'<tptz:AbsoluteMove>{PT}<tptz:Position><tt:Zoom x="1"/></tptz:Position></tptz:AbsoluteMove>')
check("AbsoluteMove zoom-only answered", "AbsoluteMoveResponse" in r, r[-300:])
check("AbsoluteMove zoom-only frame", take() == [frame(0x4F, 65535)])

r = soap(f'<tptz:AbsoluteMove>{PT}<tptz:Position><tt:PanTilt x="3" y="0"/></tptz:Position></tptz:AbsoluteMove>')
check("AbsoluteMove out of range refused", "InvalidPosition" in r and take() == [], r[-200:])

r = soap(f'<tptz:RelativeMove>{PT}<tptz:Translation><tt:Zoom x="-0.5"/></tptz:Translation></tptz:RelativeMove>')
check("RelativeMove zoom-only answered", "RelativeMoveResponse" in r, r[-300:])
f = take()
check("RelativeMove zoom-only frame", f == [frame(0x4F, 32768)], f)

r = soap(f'<tptz:RelativeMove>{PT}<tptz:Translation><tt:PanTilt x="0.25" y="0.1"/></tptz:Translation></tptz:RelativeMove>')
f = take()
check("RelativeMove pan/tilt from queried position", f == [frame(0x4B, 31500), frame(0x4D, 35100)], f)

r = soap(f'<tptz:RelativeMove>{PT}</tptz:RelativeMove>')
check("RelativeMove with nothing refused, nothing run", "InvalidTranslation" in r and take() == [], r[-200:])

r = soap(f'<tptz:ContinuousMove>{PT}<tptz:Velocity><tt:PanTilt x="0.5" y="1"/><tt:Zoom x="0.5"/>'
         f'</tptz:Velocity></tptz:ContinuousMove>')
check("ContinuousMove answered", "ContinuousMoveResponse" in r, r[-300:])
f = take()
check("ContinuousMove builds one combined motion, zoom included",
      f == ["ff 01 00 02 20 00 23", "ff 01 00 0a 20 3f 6a", "ff 01 00 2a 20 3f 8a"], f)

r = soap(f'<tptz:GetStatus>{PT}</tptz:GetStatus>')
check("GetStatus reports moving", "MOVING" in r, r[-400:])
r = soap(f'<tptz:Stop>{PT}</tptz:Stop>')
check("Stop frame", take() == [frame(0)])

r = soap(f'<tptz:GetStatus>{PT}</tptz:GetStatus>')
check("GetStatus position", 'x="-0.250000"' in r and 'y="0.100000"' in r and 'x="0.500000"' in r, r[-500:])

r = soap(f'<tptz:SetPreset>{PT}<tptz:PresetName>gate</tptz:PresetName></tptz:SetPreset>')
check("SetPreset returns token 2", "PresetToken_2" in r, r[-300:])
check("SetPreset frame", [x for x in take() if x.split()[3] == "03"] == [frame(0x03, 2)])
r = soap(f'<tptz:GetPresets>{PT}</tptz:GetPresets>')
check("GetPresets lists it", "gate" in r and "PresetToken_2" in r, r[-400:])
r = soap(f'<tptz:GotoPreset>{PT}<tptz:PresetToken>PresetToken_2</tptz:PresetToken></tptz:GotoPreset>')
check("GotoPreset frame", take() == [frame(0x07, 2)])
r = soap(f'<tptz:SetPreset>{PT}<tptz:PresetToken>PresetToken_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
         f'</tptz:PresetToken></tptz:SetPreset>')
check("SetPreset with a long token is refused, not a crash", "NoToken" in r, r[-300:])
r = soap(f'<tptz:RemovePreset>{PT}<tptz:PresetToken>PresetToken_2</tptz:PresetToken></tptz:RemovePreset>')
check("RemovePreset frame", take() == [frame(0x05, 2)])
r = soap(f'<tptz:SetHomePosition>{PT}</tptz:SetHomePosition>')
r = soap(f'<tptz:GotoHomePosition>{PT}</tptz:GotoHomePosition>')
check("home frames", take() == [frame(0x03, 1), frame(0x07, 1)])

head.stop = True
print(f"{failures} failure(s)" if failures else "onvif e2e: all passed")
sys.exit(1 if failures else 0)

general/package/anjvision-mcl18d/src/tests/af_sim.py

new, 149 lines. mcl18d-af under busybox ash against a simulated lens with backlash, noise, end stops and late snapshots.

"""mcl18d-af against a simulated lens: fake pelco-ptz, curl and cli on PATH.

The lens position is in milliseconds of motor travel, 0..1500, moved by the
time between `pelco-ptz focus` and `pelco-ptz stop` as the fakes see it, so
process start-up jitter counts as it would on the camera. Each reversal loses
BACKLASH ms. A snapshot's size is a bell curve around the in-focus position
plus noise, taken where the lens was LAG ms earlier (0 unless a case sets
it), so snapshots during a sweep see it moving, and late. Run: python3 tests/af_sim.py SH SCRIPT WORK, where SH is the
busybox ash to run it under (a host build of the tree's busybox).
"""
import os
import stat
import subprocess
import sys

SH, SCRIPT, WORK = sys.argv[1:4]
BB = os.path.join(os.path.dirname(SH), "busybox") if os.path.basename(SH) != "busybox" else SH
BIN = os.path.join(WORK, "bin")
os.makedirs(BIN, exist_ok=True)

FAKE_PTZ = r'''#!/usr/bin/env python3
import json, os, sys, time
W = os.environ["AF_WORK"]
st = json.load(open(W + "/lens"))
now = time.monotonic() * 1000
with open(W + "/calls", "a") as f:
    f.write(" ".join(sys.argv[1:]) + "\n")
if st.get("dir") and st.get("t0") is not None:
    moved = now - st["t0"]
    if st["dir"] != st.get("last"):
        moved = max(0.0, moved - st["backlash"])
        st["last"] = st["dir"]
    st["pos"] = min(1500.0, max(0.0, st["pos"] + (moved if st["dir"] == "far" else -moved)))
    st["dir"] = None
    st["t0"] = None
if sys.argv[1:2] == ["focus"]:
    st["dir"], st["t0"] = sys.argv[2], now
# Where the lens was from when, for snapshots that lag.
st.setdefault("hist", []).append([now, st["pos"], st["dir"]])
st["hist"] = st["hist"][-50:]
json.dump(st, open(W + "/lens", "w"))
'''

FAKE_CURL = r'''#!/usr/bin/env python3
import json, math, os, random, sys, time
W = os.environ["AF_WORK"]
st = json.load(open(W + "/lens"))
url = sys.argv[-1]
if st.get("need_auth") and st["need_auth"] not in sys.argv:
    print(0, end=""); sys.exit(22)
if st.get("no_crop") and "crop=" in url:
    print(0, end=""); sys.exit(22)
with open(W + "/urls", "a") as f:
    f.write(url + "\n")
when = time.monotonic() * 1000 - st.get("lag", 0)
p = st["pos"]
for t, pos, d in reversed(st.get("hist", [])):   # the last change before `when`
    if t <= when:
        p = pos
        if d:   # it was running then; backlash is left out of a lagging view
            p = min(1500.0, max(0.0, p + ((when - t) if d == "far" else -(when - t))))
        break
size = 40000 + (0 if st.get("peak_flat") else 60000) * math.exp(-((p - st["peak"]) / 250.0) ** 2)
print(int(size * (1 + random.uniform(-st["noise"], st["noise"]))), end="")
'''

FAKE_CLI = "#!/bin/sh\necho 2960x1664\n"

for name, body in (("pelco-ptz", FAKE_PTZ), ("curl", FAKE_CURL), ("cli", FAKE_CLI)):
    path = os.path.join(BIN, name)
    with open(path, "w") as f:
        f.write(body)
    os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
for applet in ("usleep", "logger", "sed"):
    try:
        os.symlink(BB, os.path.join(BIN, applet))
    except FileExistsError:
        pass

failures = 0


def check(what, cond, detail=""):
    global failures
    if cond:
        print(f"ok   {what}")
    else:
        failures += 1
        print(f"FAIL {what} {detail}")


def run(pos, peak, args=(), noise=0.005, backlash=15, **extra):
    st = dict(pos=float(pos), peak=float(peak), noise=noise, backlash=backlash, dir=None, t0=None, last=None)
    st.update(extra)
    import json
    json.dump(st, open(f"{WORK}/lens", "w"))
    for f in ("calls", "urls"):
        open(f"{WORK}/{f}", "w").close()
    env = dict(os.environ, PATH=f"{BIN}:{os.environ['PATH']}", AF_WORK=WORK)
    # The simulated lens travels 1.5 s end to end against the camera's tens of
    # seconds, so the back-off and the approach step shrink with it.
    r = subprocess.run([SH, SCRIPT, "-u", "root:pw", "-w", "20", "-t", "3", "-b", "150", "-s", "30", *args],
                       capture_output=True,
                       text=True, env=env, timeout=300)
    end = json.load(open(f"{WORK}/lens"))
    calls = open(f"{WORK}/calls").read().split("\n")
    return r, end, calls


# The approach stops on the first step that is worse, so the lens ends one
# step past the sharpest point: a 30 ms step, plus the 30 ms or so every pulse
# runs long because the fakes are Python (the real pelco-ptz is C), plus noise.
# Within 100 the picture is within 15% of its sharpest here
# (exp(-(100/250)^2) = 0.85); this bell is narrow next to the camera's, where
# the 150 ms step ended at 99.5% of the best snapshot (2026-10-29).
TOLERANCE = 100

for start, peak in ((200, 900), (1200, 600), (700, 700), (100, 1300)):
    r, end, calls = run(start, peak)
    err = abs(end["pos"] - peak)
    check(f"start {start}, focus at {peak}: ends at {end['pos']:.0f}", r.returncode == 0 and err < TOLERANCE,
          f"rc={r.returncode} err={err:.0f}\n{r.stdout}{r.stderr}")
    check(f"start {start}: motor stopped at the end", calls[-2] == "stop" and end["dir"] is None, calls[-3:])

urls = open(f"{WORK}/urls").read().split()
check("judges the middle third by default", urls[0] == "http://127.0.0.1/image.jpg?crop=986x554x986x554", urls[0])

# A snapshot that shows the lens 150 ms late: just after the second sweep turns
# round the picture is still getting worse, which once made it give up at once.
r, end, _ = run(1200, 600, args=("-w", "200"), lag=150)
check("snapshots lag 150 ms, focus behind the start: still found",
      r.returncode == 0 and abs(end["pos"] - 600) < TOLERANCE, f"rc={r.returncode} ends at {end['pos']:.0f}\n{r.stdout}")

r, end, _ = run(200, 900, no_crop=True)
check("crop refused: falls back to the full frame",
      r.returncode == 0 and "AF_CROP_REFUSED" in r.stdout and abs(end["pos"] - 900) < TOLERANCE, r.stdout + r.stderr)

r, end, calls = run(200, 900, need_auth="root:right")
check("wrong login: stops with a message, motor untouched",
      r.returncode == 2 and "AF_SNAPSHOT_FAILED" in r.stdout and end["pos"] == 200, r.stdout + r.stderr)

r, end, _ = run(500, 900, noise=0.0, peak_flat=True)
check("featureless picture: gives up, says so", r.returncode == 3 and "AF_NO_DETAIL" in r.stdout, r.stdout)

r, _, _ = run(200, 900, args=("-s", "abc"))
check("bad number refused", r.returncode == 1 and "not a number" in r.stderr, r.stderr)

print(f"{failures} failure(s)" if failures else "af sim: all passed")
sys.exit(1 if failures else 0)

5. onvif-simple-server fixes

general/package/onvif-simple-server/03-ptz-absolute-relative-zoom-fixes.patch

new, 116 lines. Applied by Buildroot to onvif-simple-server 7c8672f. The same change is on branch ptz-fixes of openipc/onvif_simple_server (its git diff has identical hunks).

ptz_service: absolute and relative moves that name only some axes

AbsoluteMove passed 0 for any axis the request left out, so every pan/tilt
position also drove the zoom fully wide; it now passes NAN ("leave it"). A
zoom-only AbsoluteMove or RelativeMove passed validation and then ran an
uninitialised command buffer through system(); both now build a command,
and a RelativeMove with neither PanTilt nor Zoom is refused. The FOV-space
relative move is scaled to the generic space the configured ranges describe.
RelativeMove no longer strcmp()s a Zoom space that may be NULL, and SetPreset
no longer sscanf()s "%s" into an int.

diff --git a/ptz_service.c b/ptz_service.c
index 58120ab..54e87af 100644
--- a/ptz_service.c
+++ b/ptz_service.c
@@ -19,6 +19,7 @@
 #include <string.h>
 #include <unistd.h>
 #include <time.h>
+#include <math.h>
 
 #include "ptz_service.h"
 #include "fault.h"
@@ -593,6 +594,9 @@ int ptz_relative_move()
         return -3;
     }
 
+    sys_command[0] = '\0';
+    node_p = NULL;
+    node_z = NULL;
     node = get_element_ptr(NULL, "Translation", "Body");
     if (node != NULL) {
         node_p = get_element_in_element_ptr("PanTilt", node);
@@ -671,20 +675,32 @@ int ptz_relative_move()
                     // Convert degrees in relative coordinates
                     // Approximation 3: I don't know how many degrees is max_step_x, assume 360°
                     // Approximation 4: I don't know how many degrees is max_step_y, assume 180°
-                    dx = dx / (360.0 / service_ctx.ptz_node.max_step_x);
-                    dy = dy / (180.0 / service_ctx.ptz_node.max_step_y);
+                    // Into the generic space the position ranges describe:
+                    // max_step_x spans 180 degrees of pan, max_step_y 90 of tilt.
+                    dx = dx / 180.0 * service_ctx.ptz_node.max_step_x;
+                    dy = dy / 90.0 * service_ctx.ptz_node.max_step_y;
                     sprintf(sys_command, service_ctx.ptz_node.jump_to_rel, dx, dy, 0);
                 }
             }
         }
     }
 
-    if (node_z != NULL) {
-        if (strcmp("http://www.onvif.org/ver10/tptz/ZoomSpaces/TranslationGenericSpace", space_z) == 0) {
-            // do nothing
+    // A zoom-only translation is a move too. (The strcmp on space_z that
+    // stood here did nothing and dereferenced NULL when Zoom had no space.)
+    if ((node_p == NULL) && (z != NULL)) {
+        dz = atof(z);
+        if ((dz > service_ctx.ptz_node.max_step_z) || (dz < -service_ctx.ptz_node.max_step_z)) {
+            ret = -7;
+        } else {
+            sprintf(sys_command, service_ctx.ptz_node.jump_to_rel, 0.0, 0.0, dz);
         }
     }
 
+    // Nothing was built: refuse rather than run an uninitialised buffer.
+    if ((ret == 0) && (sys_command[0] == '\0')) {
+        ret = -4;
+    }
+
     if (ret == 0) {
         system(sys_command);
 
@@ -706,9 +722,9 @@ int ptz_absolute_move()
     char const *x = NULL;
     char const *y = NULL;
     char const *z = NULL;
-    double dx = 0.0;
-    double dy = 0.0;
-    double dz = 0.0;
+    double dx = NAN;
+    double dy = NAN;
+    double dz = NAN;
     char sys_command_tmp[MAX_LEN];
     char sys_command[MAX_LEN];
     int ret = 0;
@@ -764,14 +780,16 @@ int ptz_absolute_move()
             if ((dy > service_ctx.ptz_node.max_step_y) || (dy < service_ctx.ptz_node.min_step_y)) {
                 ret = -6;
             }
-            if (z != NULL) {
-                dz = atof(z);
-                if ((dz > service_ctx.ptz_node.max_step_z) || (dz < service_ctx.ptz_node.min_step_z)) {
-                    ret = -7;
-                }
+        }
+        // Zoom on its own is a position too, and an axis the request leaves
+        // out reaches the command as "nan" (leave it) rather than as 0.
+        if (z != NULL) {
+            dz = atof(z);
+            if ((dz > service_ctx.ptz_node.max_step_z) || (dz < service_ctx.ptz_node.min_step_z)) {
+                ret = -7;
             }
-            sprintf(sys_command, service_ctx.ptz_node.jump_to_abs, dx, dy, dz);
         }
+        sprintf(sys_command, service_ctx.ptz_node.jump_to_abs, dx, dy, dz);
     }
 
     if (ret == 0) {
@@ -946,7 +964,7 @@ int ptz_set_preset()
 
     preset_token = get_element("PresetToken", "Body");
     if (preset_token != NULL) {
-        if (sscanf(preset_token, "PresetToken_%s", &preset_number) != 1) {
+        if (sscanf(preset_token, "PresetToken_%d", &preset_number) != 1) {
             send_fault("ptz_service", "Sender", "ter:InvalidArgVal", "ter:NoToken", "No token", "The requested preset token does not exist");
             return -3;
         }

6. Tools written for the port (not shipped on the camera)

gc5603-difftest/emu_ko.py

new, 201 lines. Loads an ARM kernel module into unicorn, applies relocations, stubs kernel symbols.

"""Load an ARM Thumb-2 kernel module (.ko) into unicorn and call its functions.

Undefined symbols resolve to Python stubs. Enough relocation types are handled
for SigmaStar sensor modules built with -mthumb.
"""
import struct

from elftools.elf.elffile import ELFFile
from elftools.elf.relocation import RelocationSection
from elftools.elf.sections import SymbolTableSection
from unicorn import Uc, UC_ARCH_ARM, UC_MODE_THUMB, UC_HOOK_CODE
from unicorn.arm_const import (
    UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3,
    UC_ARM_REG_SP, UC_ARM_REG_LR, UC_ARM_REG_PC,
)

REGS = [UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3]
CODE_BASE = 0x10000000
STUB_BASE = CODE_BASE + 0x300000  # within Thumb BL range of the code
HEAP_BASE = 0x30000000
STACK_TOP = 0x40000000
RET_MAGIC = 0x50000000


def _thm_branch_decode(h1, h2):
    s = (h1 >> 10) & 1
    imm10 = h1 & 0x3FF
    j1 = (h2 >> 13) & 1
    j2 = (h2 >> 11) & 1
    imm11 = h2 & 0x7FF
    i1 = 1 - (j1 ^ s)
    i2 = 1 - (j2 ^ s)
    off = (s << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1)
    if s:
        off -= 1 << 25
    return off


def _thm_branch_encode(h1, h2, off):
    off &= (1 << 25) - 1
    s = (off >> 24) & 1
    i1 = (off >> 23) & 1
    i2 = (off >> 22) & 1
    imm10 = (off >> 12) & 0x3FF
    imm11 = (off >> 1) & 0x7FF
    j1 = (1 - i1) ^ s
    j2 = (1 - i2) ^ s
    h1 = (h1 & 0xF800) | (s << 10) | imm10
    h2 = (h2 & 0xD000) | (j1 << 13) | (j2 << 11) | imm11
    return h1, h2


def _movw_decode(h1, h2):
    return ((h1 & 0xF) << 12) | (((h1 >> 10) & 1) << 11) | (((h2 >> 12) & 7) << 8) | (h2 & 0xFF)


def _movw_encode(h1, h2, imm):
    h1 = (h1 & 0xFBF0) | ((imm >> 12) & 0xF) | (((imm >> 11) & 1) << 10)
    h2 = (h2 & 0x8F00) | (((imm >> 8) & 7) << 12) | (imm & 0xFF)
    return h1, h2


class Module:
    def __init__(self, path, stubs):
        self.uc = Uc(UC_ARCH_ARM, UC_MODE_THUMB)
        self.stubs = {}
        self.stub_addr = {}
        self.heap_next = HEAP_BASE
        self.uc.mem_map(CODE_BASE, 0x400000)
        self.uc.mem_map(HEAP_BASE, 0x100000)
        self.uc.mem_map(STACK_TOP - 0x100000, 0x100000)
        self.uc.mem_map(RET_MAGIC, 0x1000)
        self.uc.mem_write(RET_MAGIC, b"\x70\x47" * 8)
        self.syms = {}
        self._load(path, stubs)
        self.uc.hook_add(UC_HOOK_CODE, self._stub_hook, begin=STUB_BASE, end=STUB_BASE + 0xFFFF)

    def _stub(self, name):
        if name not in self.stub_addr:
            addr = STUB_BASE + 4 * len(self.stub_addr)
            self.uc.mem_write(addr, b"\x70\x47\x00\xbf")  # bx lr; nop
            self.stub_addr[name] = addr
        return self.stub_addr[name]

    def stub_ptr(self, name, fn):
        """Return a callable address for a Python function (for vtables)."""
        self.stubs[name] = fn
        return self._stub(name) | 1

    def _load(self, path, stubs):
        f = open(path, "rb")
        elf = ELFFile(f)
        sec_addr = {}
        cur = CODE_BASE
        for i, sec in enumerate(elf.iter_sections()):
            if not (sec["sh_flags"] & 2) or sec.name.startswith(".ARM.ex"):
                continue
            align = max(sec["sh_addralign"], 4)
            cur = (cur + align - 1) & ~(align - 1)
            sec_addr[i] = cur
            data = sec.data() if sec["sh_type"] != "SHT_NOBITS" else b"\0" * sec["sh_size"]
            self.uc.mem_write(cur, data)
            cur += sec["sh_size"]
        symtab = elf.get_section_by_name(".symtab")
        symvals = []
        for sym in symtab.iter_symbols():
            shndx = sym["st_shndx"]
            if shndx == "SHN_UNDEF":
                if sym.name:
                    self.stubs.setdefault(sym.name, stubs.get(sym.name))
                    symvals.append(self._stub(sym.name) | 1)
                else:
                    symvals.append(0)
            elif isinstance(shndx, int) and shndx in sec_addr:
                v = sec_addr[shndx] + sym["st_value"]
                symvals.append(v)
                if sym.name and sym["st_info"]["type"] in ("STT_FUNC", "STT_OBJECT"):
                    self.syms[sym.name] = v
            else:
                symvals.append(0)
        for sec in elf.iter_sections():
            if not isinstance(sec, RelocationSection):
                continue
            target = sec["sh_info"]
            if target not in sec_addr:
                continue
            base = sec_addr[target]
            for rel in sec.iter_relocations():
                p = base + rel["r_offset"]
                s = symvals[rel["r_info_sym"]]
                t = rel["r_info_type"]
                if t == 2:  # ABS32
                    a = struct.unpack("<I", self.uc.mem_read(p, 4))[0]
                    self.uc.mem_write(p, struct.pack("<I", (s + a) & 0xFFFFFFFF))
                elif t == 3:  # REL32
                    a = struct.unpack("<I", self.uc.mem_read(p, 4))[0]
                    self.uc.mem_write(p, struct.pack("<I", (s + a - p) & 0xFFFFFFFF))
                elif t in (10, 30):  # THM_CALL, THM_JUMP24
                    h1, h2 = struct.unpack("<HH", self.uc.mem_read(p, 4))
                    a = _thm_branch_decode(h1, h2)
                    off = (s & ~1) + a - p
                    if t == 10:
                        h2 |= 0x1000  # always BL, targets are Thumb
                    h1, h2 = _thm_branch_encode(h1, h2, off)
                    self.uc.mem_write(p, struct.pack("<HH", h1, h2))
                elif t in (47, 48):  # THM_MOVW_ABS_NC, THM_MOVT_ABS
                    h1, h2 = struct.unpack("<HH", self.uc.mem_read(p, 4))
                    a = _movw_decode(h1, h2)
                    if a & 0x8000:
                        a -= 0x10000
                    v = (s + a) & 0xFFFFFFFF
                    v = v & 0xFFFF if t == 47 else v >> 16
                    h1, h2 = _movw_encode(h1, h2, v)
                    self.uc.mem_write(p, struct.pack("<HH", h1, h2))
                elif t == 42:  # PREL31 (unwind tables)
                    pass
                else:
                    raise ValueError("unhandled relocation type %d at %x" % (t, p))
        f.close()

    def _stub_hook(self, uc, addr, size, _):
        name = next(n for n, a in self.stub_addr.items() if a == (addr & ~1))
        fn = self.stubs.get(name)
        if fn is None:
            raise RuntimeError("call to unimplemented stub %s" % name)
        args = [uc.reg_read(r) for r in REGS]
        sp = uc.reg_read(UC_ARM_REG_SP)
        ret = fn(self, args, sp)
        if ret is not None:
            uc.reg_write(UC_ARM_REG_R0, ret & 0xFFFFFFFF)

    def alloc(self, size):
        addr = self.heap_next
        self.heap_next += (size + 15) & ~15
        self.uc.mem_write(addr, b"\0" * size)
        return addr

    def call(self, name, *args):
        addr = self.syms[name]
        for r, v in zip(REGS, args):
            self.uc.reg_write(r, v & 0xFFFFFFFF)
        self.uc.reg_write(UC_ARM_REG_SP, STACK_TOP - 0x100)
        self.uc.reg_write(UC_ARM_REG_LR, RET_MAGIC | 1)
        self.uc.emu_start(addr | 1, RET_MAGIC, count=2_000_000)
        r0 = self.uc.reg_read(UC_ARM_REG_R0)
        return r0 - (1 << 32) if r0 & 0x80000000 else r0

    def r32(self, addr):
        return struct.unpack("<I", self.uc.mem_read(addr, 4))[0]

    def w32(self, addr, v):
        self.uc.mem_write(addr, struct.pack("<I", v & 0xFFFFFFFF))

    def cstr(self, addr):
        out = b""
        while True:
            c = bytes(self.uc.mem_read(addr, 1))
            if c == b"\0":
                return out
            out += c
            addr += 1

gc5603-difftest/difftest.py

new, 192 lines. Runs the vendor and the rebuilt sensor drivers side by side and compares every I2C transaction.

"""Differential test: vendor gc5603_MIPI_1125.ko vs the rebuilt sensor_gc5603_mipi.ko.

Both run in unicorn against the same fake sensor. Every I2C transaction and
every value a getter returns must match. Orientation is compared through the
documented remap (rebuilt orit k == vendor orit 3-k).
"""
import os
import random
import struct
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from emu_ko import Module  # noqa: E402




def u32(m, a):
    return m.r32(a)


def make_stubs():
    def memcpy(m, a, sp):
        m.uc.mem_write(a[0], bytes(m.uc.mem_read(a[1], a[2])))
        return a[0]

    def memset(m, a, sp):
        m.uc.mem_write(a[0], bytes([a[1] & 0xFF]) * a[2])
        return a[0]

    def strcpy(m, a, sp):
        m.uc.mem_write(a[0], m.cstr(a[1]) + b"\0")
        return a[0]

    def sprintf(m, a, sp):
        m.uc.mem_write(a[0], m.cstr(a[1]) + b"\0")
        return 0

    def msleep(m, a, sp):
        m.log.append(("sleep_ms", a[0]))

    def uidiv(m, a, sp):
        return a[0] // a[1]

    def idiv(m, a, sp):
        x = a[0] - (1 << 32) if a[0] & 0x80000000 else a[0]
        y = a[1] - (1 << 32) if a[1] & 0x80000000 else a[1]
        return int(x / y)

    nop = lambda m, a, sp: 0
    return {
        "memcpy": memcpy, "memset": memset, "strcpy": strcpy, "sprintf": sprintf,
        "msleep": msleep, "__aeabi_uidiv": uidiv, "__aeabi_idiv": idiv,
        "CamOsUsSleep": nop, "CamOsMsSleep": nop, "CamOsPrintf": nop, "printk": nop,
        "_printk": nop,
    }


class Sensor:
    def __init__(self):
        self.regs = {0x03F0: 0x56, 0x03F1: 0x03, 0x0410: 0, 0x0414: 0}


def setup(path, layout, sensor):
    m = Module(path, make_stubs())
    m.log = []

    def tx(mm, a, sp):
        mm.log.append(("w", a[2] & 0xFFFF, a[3] & 0xFFFF))
        return 0

    def rx(mm, a, sp):
        reg = a[2] & 0xFFFF
        mm.log.append(("r", reg))
        mm.uc.mem_write(a[3], struct.pack("<H", sensor.regs.get(reg, 0)))
        return 0

    def atx(mm, a, sp):
        pairs = [struct.unpack("<HH", bytes(mm.uc.mem_read(a[2] + 4 * i, 4))) for i in range(a[3])]
        mm.log.append(("aw", tuple(pairs)))
        return 0

    def arx(mm, a, sp):
        for i in range(a[3]):
            reg = struct.unpack("<H", bytes(mm.uc.mem_read(a[2] + 4 * i, 2)))[0]
            mm.uc.mem_write(a[2] + 4 * i + 2, struct.pack("<H", sensor.regs.get(reg, 0)))
        mm.log.append(("ar", a[3]))
        return 0

    handle = m.alloc(0x1000)
    params = m.alloc(0x400)
    bus = m.alloc(0x100)
    m.w32(handle + 0x28, params)
    m.w32(handle + layout["bus"], bus)
    for key, fn in (("tx", tx), ("rx", rx), ("atx", atx), ("arx", arx)):
        m.w32(bus + layout[key], m.stub_ptr("i2c_" + key, fn))
    m.handle = handle
    m.layout = layout
    return m


VENDOR_LAYOUT = {"bus": 0x3C, "tx": 20, "rx": 24, "atx": 28, "arx": 40,
                 "res": 0x90, "i2c_addr": 0x38, "sat_mingain": 0x9BC, "mclk": 0x9B8}
MINE_LAYOUT = {"bus": 0x3C, "tx": 20, "rx": 24, "atx": 28, "arx": 40,
               "res": 0xA0, "i2c_addr": 0x38, "sat_mingain": 0x9CC, "mclk": 0x9C8}


def take(m):
    out, m.log = m.log, []
    return out


def main():
    VENDOR, MINE = sys.argv[1], sys.argv[2]
    sensor = Sensor()
    v = setup(VENDOR, VENDOR_LAYOUT, sensor)
    n = setup(MINE, MINE_LAYOUT, sensor)
    failures = 0
    checks = 0

    def same(what, a, b):
        nonlocal failures, checks
        checks += 1
        if a != b:
            failures += 1
            if failures <= 15:
                print("MISMATCH %s\n  vendor: %s\n  mine:   %s" % (what, a, b))

    same("init_handle", v.call("cus_camsensor_init_handle", v.handle), n.call("cus_camsensor_init_handle", n.handle))
    same("model_id", v.cstr(v.handle + 4), n.cstr(n.handle + 4))
    for i, name in enumerate(("width", "height", "max_fps", "min_fps")):
        same(name, u32(v, v.handle + VENDOR_LAYOUT["res"] + 4 * i), u32(n, n.handle + MINE_LAYOUT["res"] + 4 * i))
    for key in ("i2c_addr", "sat_mingain", "mclk"):
        mask = 0xFFFF if key == "i2c_addr" else 0xFFFFFFFF
        same(key, u32(v, v.handle + VENDOR_LAYOUT[key]) & mask, u32(n, n.handle + MINE_LAYOUT[key]) & mask)

    same("init ret", v.call("pCus_init", v.handle), n.call("pCus_init", n.handle))
    same("init io", take(v), take(n))

    idv, idn = v.alloc(4), n.alloc(4)
    same("id ret", v.call("pCus_GetSensorID", v.handle, idv), n.call("pCus_GetSensorID", n.handle, idn))
    same("id", v.r32(idv), n.r32(idn))
    take(v), take(n)

    gains = [0, 500, 1023, 1024, 1183, 1184, 5000, 8191, 8192, 16383, 16384, 20000, 32767, 32768,
             50000, 63439, 63440, 65535, 65536, 81919, 81920, 100000, 131071, 131072, 200000]
    los = [0, 3, 5, 6, 11, 12, 15, 16, 27, 28, 29, 32, 33, 40, 41, 51, 52, 69, 70, 200, 255]
    his = [0, 0, 0, 1, 1, 2]
    rng = random.Random(5603)
    out_v, out_n = v.alloc(8), n.alloc(8)

    for step in range(20000):
        op = rng.random()
        sensor.regs[0x0410] = rng.choice(los)
        sensor.regs[0x0414] = rng.choice(his)
        if op < 0.55:
            g = rng.choice(gains) if rng.random() < 0.6 else rng.randint(0, 200000)
            a = v.call("pCus_SetAEGain", v.handle, g)
            b = n.call("pCus_SetAEGain", n.handle, g)
            same("SetAEGain(%d) ret" % g, a, b)
            same("SetAEGain(%d) io lo=%d hi=%d" % (g, sensor.regs[0x410], sensor.regs[0x414]), take(v), take(n))
        elif op < 0.70:
            us = rng.choice([0, 1, 19, 20, 30, 1000, 33333, 40000, 100000, 200000, 1000000])
            same("SetAEUSecs(%d)" % us, v.call("pCus_SetAEUSecs", v.handle, us), n.call("pCus_SetAEUSecs", n.handle, us))
        elif op < 0.78:
            fps = rng.choice([1, 4, 5, 10, 15, 20, 25, 30, 31, 4999, 5000, 12500, 25000, 29970, 30000, 30001])
            same("SetFPS(%d)" % fps, v.call("pCus_SetFPS", v.handle, fps), n.call("pCus_SetFPS", n.handle, fps))
            same("GetFPS", v.call("pCus_GetFPS", v.handle), n.call("pCus_GetFPS", n.handle))
        elif op < 0.83:
            k = rng.randint(0, 3)
            same("SetOrien", v.call("pCus_SetOrien", v.handle, 3 - k), n.call("pCus_SetOrien", n.handle, k))
        else:
            same("Notify ret", v.call("pCus_AEStatusNotify", v.handle, 1), n.call("pCus_AEStatusNotify", n.handle, 1))
            same("Notify io", take(v), take(n))
        v.call("pCus_GetAEGain", v.handle, out_v)
        n.call("pCus_GetAEGain", n.handle, out_n)
        same("GetAEGain", v.r32(out_v), n.r32(out_n))
        v.call("pCus_GetAEUSecs", v.handle, out_v)
        n.call("pCus_GetAEUSecs", n.handle, out_n)
        same("GetAEUSecs", v.r32(out_v), n.r32(out_n))

    for name in ("pCus_GetAEMinMaxGain", "pCus_GetAEMinMaxUSecs"):
        v.call(name, v.handle, out_v, out_v + 4)
        n.call(name, n.handle, out_n, out_n + 4)
        same(name, (v.r32(out_v), v.r32(out_v + 4)), (n.r32(out_n), n.r32(out_n + 4)))

    print("checks: %d  mismatches: %d" % (checks, failures))
    sys.exit(1 if failures else 0)


if __name__ == "__main__":
    main()

af-board-re/plt.py

new, 50 lines. Maps PLT stubs to their real imported symbol (r2/objdump name them one entry off).

"""Map ARM PLT stub addresses to the imported symbol they jump to.

r2 and objdump label these stubs one entry off in the vendor binaries, which
names every libc call wrongly; this reads the stubs themselves
(add ip,pc / add ip,ip / ldr pc,[ip]) and follows them to their JUMP_SLOT."""
import re
import struct
import subprocess
import sys


def _sections(elf):
    secs = {}
    out = subprocess.run(['readelf', '-SW', elf], capture_output=True, text=True).stdout
    for line in out.splitlines():
        m = re.match(r'\s*\[\s*\d+\]\s+(\S+)\s+\S+\s+([0-9a-f]+)\s+([0-9a-f]+)\s+([0-9a-f]+)', line)
        if m:
            secs[m.group(1)] = tuple(int(m.group(i), 16) for i in (2, 3, 4))
    return secs


def plt_map(elf):
    d = open(elf, 'rb').read()
    slot = {}
    for line in subprocess.run(['readelf', '-rW', elf], capture_output=True, text=True).stdout.splitlines():
        p = line.split()
        if len(p) >= 5 and 'JUMP_SLOT' in line:
            slot[int(p[0], 16)] = p[4].split('@')[0]

    def rot(v):
        imm, r = v & 0xff, ((v >> 8) & 0xf) * 2
        return ((imm >> r) | (imm << (32 - r))) & 0xffffffff

    pa, po, ps = _sections(elf)['.plt']
    out, a = {}, pa + 20
    while a < pa + ps:
        w = struct.unpack_from('<3I', d, po + a - pa)
        if (w[0] & 0xfffff000) == 0xe28fc000 and (w[1] & 0xfffff000) == 0xe28cc000 \
                and (w[2] & 0xfffff000) == 0xe5bcf000:
            got = (a + 8 + rot(w[0]) + rot(w[1]) + (w[2] & 0xfff)) & 0xffffffff
            out[a] = slot.get(got, '?')
            a += 12
        else:
            a += 4  # thumb "bx pc; nop" prefix
    return out


if __name__ == '__main__':
    for a, n in sorted(plt_map(sys.argv[1]).items()):
        print(f'{a:x} {n}')

af-board-re/od.py

new, 72 lines. Annotated disassembler: resolves movw/movt pairs, literal pools and PLT names.

"""Annotated thumb disassembly of a vendor binary: od.py ELF START END (hex).

Wraps arm-none-eabi-objdump and adds: real import names on PLT calls,
movw/movt pairs and literal-pool loads resolved to strings or globals."""
import os
import re
import struct
import subprocess
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from plt import _sections, plt_map  # noqa: E402

elf, start, end = sys.argv[1], int(sys.argv[2], 16), int(sys.argv[3], 16)
d = open(elf, 'rb').read()
secs = _sections(elf)
plt = plt_map(elf)
segs = []
for line in subprocess.run(['readelf', '-lW', elf], capture_output=True, text=True).stdout.splitlines():
    q = line.split()
    if q and q[0] == 'LOAD':
        segs.append((int(q[2], 16), int(q[1], 16), int(q[4], 16)))


def v2o(v):
    for va, off, fs in segs:
        if va <= v < va + fs:
            return off + v - va


def describe(v):
    a, o, s = secs['.rodata']
    if a <= v < a + s:
        st = d[o + v - a:d.find(b'\0', o + v - a)]
        if len(st) >= 2 and all(32 <= c < 127 or c in (9, 10, 13) for c in st):
            return repr(st.decode())[:70]
        return 'rodata ' + d[o + v - a:o + v - a + 16].hex(' ')
    for n in ('.data', '.bss', '.data.rel.ro'):
        if n in secs and secs[n][0] <= v < secs[n][0] + secs[n][2]:
            return f'g_{v:x}'
    return None


out = subprocess.run(['arm-none-eabi-objdump', '-d', '-M', 'force-thumb', f'--start-address={start:#x}',
                      f'--stop-address={end:#x}', elf], capture_output=True, text=True).stdout
regs = {}
for line in out.splitlines():
    m = re.match(r'\s*([0-9a-f]+):\s+(?:[0-9a-f]{4}\s?){1,2}\s+(\S+)\s*(.*)', line)
    if not m:
        continue
    a, op, args = int(m.group(1), 16), m.group(2), m.group(3)
    ann = ''
    mm = re.match(r'(movw|movt)\w*\s+(r\d+|ip|lr|sl|fp|sb), #(\d+)', op + ' ' + args)
    if mm:
        r, v = mm.group(2), int(mm.group(3))
        if mm.group(1) == 'movw':
            regs[r] = v
        else:
            regs[r] = (regs.get(r, 0) & 0xffff) | (v << 16)
            x = describe(regs[r])
            ann = f'  ; {regs[r]:#x}' + (f' {x}' if x else '')
    lm = re.search(r'\[pc, #-?\d+\]\s*@ \(([0-9a-f]+)', args)
    if lm and op.startswith('ldr') and not op.startswith('ldrd') and v2o(int(lm.group(1), 16)) is not None:
        v = struct.unpack_from('<I', d, v2o(int(lm.group(1), 16)))[0]
        x = describe(v) or (plt.get(v & ~1) or f'fn_{v & ~1:x}' if 0x10000 <= v < 0x400000 else None)
        args = re.sub(r'\s*@ \(.*', '', args)
        ann = f'  ; ={v:#x}' + (f' {x}' if x else '')
    cm = re.match(r'([0-9a-f]+) <[^>]*>', args)
    if op.startswith('b') and cm:
        t = int(cm.group(1), 16)
        args = f'{t:x} <{plt[t]}>' if t in plt else f'{t:x}'
    print(f'{a:6x}  {op:8s} {args}{ann}')

af-board-re/emu.py

new, 267 lines. Runs vendor comm_server/media_server functions in unicorn with libc stubbed.

"""Run functions of a vendor ARM (thumb) userland binary in unicorn with libc and
vendor-library imports replaced by Python stubs. Used to read off the exact
bytes comm_server / media_server put on the lens-board UART."""
import struct, sys, re
from unicorn import Uc, UC_ARCH_ARM, UC_MODE_ARM, UC_HOOK_CODE, UC_HOOK_MEM_UNMAPPED, UcError
from unicorn.arm_const import *

REGS = [UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3]
HEAP, HEAP_SZ = 0x20000000, 0x1000000
STACK_TOP, STACK_SZ = 0x7f000000, 0x200000
RET_MAGIC = 0x7ff00000
BX_LR = struct.pack('<I', 0xe12fff1e)


class Emu:
    def __init__(self, elf, pltmap, product=0x681, verbose=False):
        """pltmap: {stub address: import name}, from plt.plt_map()."""
        self.uc = uc = Uc(UC_ARCH_ARM, UC_MODE_ARM)
        self.verbose = verbose
        d = open(elf, 'rb').read()
        phoff, phentsize, phnum = struct.unpack_from('<I', d, 0x1c)[0], *struct.unpack_from('<HH', d, 0x2a)
        hi = 0
        segs = []
        for i in range(phnum):
            t, off, va, pa, fsz, msz = struct.unpack_from('<6I', d, phoff + i * phentsize)
            if t == 1:
                segs.append((off, va, fsz, msz))
                hi = max(hi, va + msz)
        lo = segs[0][1] & ~0xfff
        uc.mem_map(lo, ((hi - lo) + 0xfffff) & ~0xfff)
        for off, va, fsz, msz in segs:
            uc.mem_write(va, d[off:off + fsz])
        uc.mem_map(HEAP, HEAP_SZ)
        uc.reg_write(UC_ARM_REG_C1_C0_2, uc.reg_read(UC_ARM_REG_C1_C0_2) | (0xf << 20))
        uc.reg_write(UC_ARM_REG_FPEXC, 0x40000000)
        uc.mem_map(STACK_TOP - STACK_SZ, STACK_SZ)
        uc.mem_map(RET_MAGIC, 0x1000)
        uc.mem_write(RET_MAGIC, BX_LR)
        self.heap = HEAP + 0x1000
        self.errno = self.alloc(4)
        self.stub = dict(pltmap)
        for a in self.stub:
            uc.mem_write(a, BX_LR)
        lo_p, hi_p = min(self.stub), max(self.stub)
        uc.hook_add(UC_HOOK_CODE, self._hook, begin=lo_p, end=hi_p + 4)
        uc.hook_add(UC_HOOK_MEM_UNMAPPED, self._bad)
        self.product = product
        self.flags = set()          # paths access() reports as present
        self.files = {}             # path -> bytes for read_file_to_string/fopen
        self.uart = []              # (fd, bytes)
        self.log = []
        self.clock_ms = 1_000_000
        self.calls = []
        self.overrides = {}

    # --- memory helpers ---------------------------------------------------
    def alloc(self, n, data=None):
        a = self.heap
        self.heap += (n + 15) & ~15
        self.uc.mem_write(a, data if data is not None else b'\0' * n)
        return a

    def r32(self, a): return struct.unpack('<I', self.uc.mem_read(a, 4))[0]
    def w32(self, a, v): self.uc.mem_write(a, struct.pack('<I', v & 0xffffffff))
    def w8(self, a, v): self.uc.mem_write(a, bytes([v & 0xff]))

    def cstr(self, a, maxn=4096):
        if a == 0:
            return b''
        out = bytearray()
        while len(out) < maxn:
            c = self.uc.mem_read(a + len(out), 64)
            i = c.find(b'\0')
            if i >= 0:
                out += c[:i]
                return bytes(out)
            out += c
        return bytes(out)

    def _bad(self, uc, access, addr, size, value, _):
        pc = uc.reg_read(UC_ARM_REG_PC)
        print(f'!! unmapped access {addr:#x} at pc {pc:#x}', file=sys.stderr)
        return False

    # --- printf ------------------------------------------------------------
    def fmt(self, f, args):
        it = iter(args)
        def rep(m):
            spec = m.group(0)
            conv = spec[-1]
            if conv == '%':
                return '%'
            v = next(it)
            if conv == 's':
                return self.cstr(v).decode('latin1')
            if conv in 'fFeEgG':
                return spec  # doubles are passed in pairs; not needed here
            if conv in 'di':
                v = v - (1 << 32) if v & 0x80000000 else v
            pyspec = re.sub(r'[hlLqjzt]', '', spec)
            try:
                return pyspec % v
            except Exception:
                return spec
        return re.sub(r'%[-+ #0]*\d*(?:\.\d+)?[hlLqjzt]*[diouxXcsfFeEgGp%]', rep, f.decode('latin1'))

    def args(self, n_reg_first):
        sp = self.uc.reg_read(UC_ARM_REG_SP)
        regs = [self.uc.reg_read(r) for r in REGS]
        def gen():
            for r in regs[n_reg_first:]:
                yield r
            k = 0
            while True:
                yield self.r32(sp + 4 * k)
                k += 1
        return gen()

    # --- dispatch -----------------------------------------------------------
    def _hook(self, uc, addr, size, _):
        n = self.stub.get(addr)
        if n is None:
            return
        a = [uc.reg_read(r) for r in REGS]
        name = n.split('@')[0]
        fn = self.overrides.get(name) or getattr(self, 's_' + name, None)
        self.calls.append(name)
        if fn is None:
            if self.verbose:
                self.log.append(f'[stub {name}]')
            r = 0
        else:
            r = fn(*a)
        if isinstance(r, tuple):
            uc.reg_write(UC_ARM_REG_R0, r[0] & 0xffffffff)
            uc.reg_write(UC_ARM_REG_R1, r[1] & 0xffffffff)
        elif r is not None:
            uc.reg_write(UC_ARM_REG_R0, r & 0xffffffff)

    def fake(self, addr, fn):
        """Replace the thumb function at addr with a Python callable(r0..r3).
        A float return is placed in s0 (VFP hard-float ABI)."""
        self.uc.mem_write(addr, b'\x70\x47')  # bx lr
        def hook(uc, a, size, _):
            r = fn(*[uc.reg_read(x) for x in REGS])
            if isinstance(r, float):
                uc.reg_write(UC_ARM_REG_S0, struct.unpack('<I', struct.pack('<f', r))[0])
            elif r is not None:
                uc.reg_write(UC_ARM_REG_R0, r & 0xffffffff)
        self.uc.hook_add(UC_HOOK_CODE, hook, begin=addr, end=addr)

    def call(self, addr, *args, stack_args=(), count=5_000_000):
        sp = STACK_TOP - 0x10000
        for i, v in enumerate(stack_args):
            self.w32(sp + 4 * i, v)
        for r, v in zip(REGS, args):
            self.uc.reg_write(r, v & 0xffffffff)
        self.uc.reg_write(UC_ARM_REG_SP, sp)
        self.uc.reg_write(UC_ARM_REG_LR, RET_MAGIC)
        try:
            self.uc.emu_start(addr | 1, RET_MAGIC, count=count)
        except UcError as e:
            pc = self.uc.reg_read(UC_ARM_REG_PC)
            raise RuntimeError(f'emulation error {e} at pc {pc:#x}')
        return self.uc.reg_read(UC_ARM_REG_R0)

    # --- libc ---------------------------------------------------------------
    def s_strcmp(self, a, b, *_):
        x, y = self.cstr(a), self.cstr(b)
        return (x > y) - (x < y)
    s_strcasecmp = lambda self, a, b, *_: self.s_strcmp(a, b)
    def s_strncmp(self, a, b, n, *_):
        x, y = self.cstr(a)[:n], self.cstr(b)[:n]
        return (x > y) - (x < y)
    def s_strstr(self, a, b, *_):
        h = self.cstr(a); i = h.find(self.cstr(b))
        return 0 if i < 0 else a + i
    def s_strchr(self, a, c, *_):
        h = self.cstr(a); i = h.find(bytes([c & 0xff]))
        return 0 if i < 0 else a + i
    def s_strrchr(self, a, c, *_):
        h = self.cstr(a); i = h.rfind(bytes([c & 0xff]))
        return 0 if i < 0 else a + i
    def s_strlen(self, a, *_): return len(self.cstr(a))
    def s_strcpy(self, d, s, *_):
        self.uc.mem_write(d, self.cstr(s) + b'\0'); return d
    def s_stpcpy(self, d, s, *_):
        b = self.cstr(s); self.uc.mem_write(d, b + b'\0'); return d + len(b)
    def s_strncpy(self, d, s, n, *_):
        b = self.cstr(s)[:n]; self.uc.mem_write(d, b + b'\0' * (n - len(b))); return d
    def s_memcpy(self, d, s, n, *_):
        if n: self.uc.mem_write(d, bytes(self.uc.mem_read(s, n)))
        return d
    def s_memset(self, d, c, n, *_):
        if n: self.uc.mem_write(d, bytes([c & 0xff]) * n)
        return d
    def s_memcmp(self, a, b, n, *_):
        x, y = bytes(self.uc.mem_read(a, n)), bytes(self.uc.mem_read(b, n))
        return (x > y) - (x < y)
    def s_atoi(self, a, *_):
        m = re.match(rb'\s*([-+]?\d+)', self.cstr(a)); return int(m.group(1)) if m else 0
    s_atol = s_atoi
    def s_tolower(self, c, *_): return ord(chr(c & 0xff).lower())
    def s_sprintf(self, d, f, *_):
        s = self.fmt(self.cstr(f), self.args(2)).encode('latin1')
        self.uc.mem_write(d, s + b'\0'); return len(s)
    def s_snprintf(self, d, n, f, *_):
        s = self.fmt(self.cstr(f), self.args(3)).encode('latin1')
        if n: self.uc.mem_write(d, s[:n - 1] + b'\0')
        return len(s)
    def s_printf(self, f, *_):
        self.log.append('printf: ' + self.fmt(self.cstr(f), self.args(1)).rstrip()); return 0
    def s_puts(self, s, *_):
        self.log.append('puts: ' + self.cstr(s).decode('latin1')); return 0
    def s_DebugPrint(self, lvl, mod, f, *_):
        self.log.append('dbg: ' + self.fmt(self.cstr(f), self.args(3)).rstrip()); return 0
    def s_access(self, p, *_):
        return 0 if self.cstr(p).decode('latin1') in self.flags else -1
    def s_FileExist(self, p, *_):
        return 1 if self.cstr(p).decode('latin1') in self.flags else 0
    def s_read_file_to_string(self, p, buf, n, *_):
        b = self.files.get(self.cstr(p).decode('latin1'))
        if b is None: return -1
        self.uc.mem_write(buf, b[:n - 1] + b'\0'); return len(b[:n - 1])
    s_read_file_to_buffer = s_read_file_to_string
    def s_write(self, fd, buf, n, *_):
        b = bytes(self.uc.mem_read(buf, n)); self.uart.append((fd, b))
        self.log.append(f'WRITE fd={fd} {b.hex(" ")}'); return n
    def s_read(self, fd, buf, n, *_): return -1
    def s_select(self, *_): return 0
    def s_open64(self, p, *_):
        self.log.append(f'open {self.cstr(p).decode("latin1")}'); return -1
    def s_fopen64(self, p, *_):
        self.log.append(f'fopen {self.cstr(p).decode("latin1")}'); return 0
    def s_close(self, *_): return 0
    def s_usleep(self, us, *_): self.clock_ms += us // 1000; return 0
    def s_sleep(self, s, *_): self.clock_ms += s * 1000; return 0
    def s_time(self, p, *_):
        t = self.clock_ms // 1000
        if p: self.w32(p, t)
        return t
    def s_GetCurrentTimeStamp(self, *_): return self.clock_ms // 1000
    def s_GetCurrentTimeStampRelative(self, *_): return self.clock_ms // 1000
    def s_SystemGetTimeofRun(self, *_): return self.clock_ms // 1000
    def s_gettimeofday(self, tv, *_):
        if tv: self.w32(tv, self.clock_ms // 1000); self.w32(tv + 4, (self.clock_ms % 1000) * 1000)
        return 0
    def s_mysystem(self, c, *_): self.log.append('system: ' + self.cstr(c).decode('latin1')); return 0
    s_system = s_mysystem
    def s_mysystem_with_param(self, f, *_):
        self.log.append('system: ' + self.fmt(self.cstr(f), self.args(1))); return 0
    def s_malloc(self, n, *_): return self.alloc(max(n, 4))
    def s_calloc(self, a, b, *_): return self.alloc(max(a * b, 4))
    s__Znwj = s_malloc
    s__Znaj = s_malloc
    def s___errno_location(self, *_): return self.errno
    def s_product_type_read(self, *_): return self.product
    def s___aeabi_idiv(self, a, b, *_):
        a = a - (1 << 32) if a & 0x80000000 else a; b = b - (1 << 32) if b & 0x80000000 else b
        return int(a / b) if b else 0
    def s___aeabi_uidiv(self, a, b, *_): return a // b if b else 0
    def s___aeabi_idivmod(self, a, b, *_):
        a = a - (1 << 32) if a & 0x80000000 else a; b = b - (1 << 32) if b & 0x80000000 else b
        q = int(a / b) if b else 0; return (q, a - q * b)
    def s___aeabi_uidivmod(self, a, b, *_): return (a // b, a % b) if b else (0, 0)
    def s_localtime_r(self, t, tm, *_):
        self.uc.mem_write(tm, b'\0' * 44); return tm

af-board-re/verify.py

new, 302 lines. Re-derives every lens-board frame in AF-BOARD-PROTOCOL.md from the vendor binaries: 40 checks.

"""Re-derive the MC-L18D lens-board protocol from the vendor binaries.

Runs the vendor's own comm_server code in unicorn (libc and vendor-library
calls stubbed in emu.py) and checks every frame AF-BOARD-PROTOCOL.md quotes:
the PTZ verbs, the version queries, the firmware upgrade handshake and the
AF / coordinate pass-through. Nothing here needs the camera.

    python3 verify.py [path/to/flash_dump_ssc377d]

Needs: python3 with unicorn (pip install unicorn), readelf.
"""
import os
import struct
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from emu import Emu  # noqa: E402
from plt import plt_map  # noqa: E402

ROOT = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, '../vendor/flash_dump_ssc377d'))
CS = f'{ROOT}/rootfs/opt/ch/comm_server'
PLT = plt_map(CS)
FD = 5
G = 0x6b998               # comm_server's flag block, filled by main() from /opt/ch/*.flag and filesys.ver
AF_FLAG = G + 0x68        # /opt/ch/af.flag
AF_PROTO5 = G + 0x74      # /opt/ch/af_protocol_5_flag
CUST_MY = G + 0x0c        # "_MY" in /etc/filesys.ver
PRODUCT = 0x66894         # product_type_read(), cached by main()
PTZ_FD = 0x66890
HANDLE_YUNTAI = 0x43408   # upgrade guard, then HandleYuntai(cmd, fd, out, outlen)
GET_AF_VERSION = 0x1bd64
GET_AF_VERSION_EX = 0x1b8a8
TTL_UPGRADE = 0x1c270     # ttl_upgrade_proc_public(path)

failures = 0


def check(what, got, want):
    global failures
    if got == want:
        print(f'ok   {what}')
    else:
        failures += 1
        print(f'FAIL {what}\n     got  {got!r}\n     want {want!r}')


def make(flags=()):
    e = Emu(CS, PLT, product=0x681)

    def access(p, *_):
        p = e.cstr(p).decode('latin1')
        if p.startswith('/mnt/nand/'):
            q = f'{ROOT}/data/' + p[10:]
        elif p.startswith('/tmp/'):
            return -1
        else:
            q = f'{ROOT}/rootfs' + p
        return 0 if os.path.exists(q) else -1
    e.overrides['access'] = access
    e.overrides['FileExist'] = lambda p, *_: 1 + access(p)
    for f in ('/etc/filesys.ver', '/etc/flag.customize'):
        e.files[f] = open(f'{ROOT}/rootfs{f}', 'rb').read()
    e.w32(AF_FLAG, 1)
    e.w32(PRODUCT, 0x681)
    e.w32(PTZ_FD, FD)
    for a in flags:
        e.w32(a, 1)
    return e


def ptz(e, name, speed=32, preset=0, data=b''):
    s = e.alloc(184)                      # the vendor's PTZ command struct
    e.uc.mem_write(s, name.encode() + b'\0')
    if data:
        e.uc.mem_write(s + 32, data)
        e.w8(s + 160, len(data))
    e.w32(s + 164, speed)
    e.w32(s + 168, speed)
    e.w8(s + 172, preset)
    e.uart.clear()
    e.call(HANDLE_YUNTAI, s, FD, e.alloc(8192), 8192)
    return [b.hex(' ') for _, b in e.uart]


def board(e, replies):
    """Wire read()/select() to a byte stream the fake lens board sends."""
    stream = bytearray(replies)
    e.overrides['select'] = lambda *a: 1 if stream else 0
    e.overrides['open64'] = lambda *a: 7

    def rd(fd, buf, n, *_):
        b = bytes(stream[:n])
        del stream[:n]
        e.uc.mem_write(buf, b)
        return len(b)
    e.overrides['read'] = rd


def pelco(b1, b2, b3, b4):
    f = bytes([0xff, 0x01, b1, b2, b3, b4])
    return (f + bytes([sum(f[1:]) & 0xff])).hex(' ')


def wrap(cmd, payload):
    f = bytes([0x51, 0x01, 0x04, 0x79, cmd, len(payload)]) + payload
    return (f + bytes([sum(f) & 0xff])).hex(' ')


# --- PTZ verbs, as this camera is configured (af.flag, customer _ASKP) ---------
e = make()
want = {
    'up': pelco(0, 0x08, 0, 0x1e), 'down': pelco(0, 0x10, 0, 0x1e),
    'left': pelco(0, 0x04, 0x1e, 0), 'right': pelco(0, 0x02, 0x1e, 0),
    'left_up': pelco(0, 0x0c, 0x1e, 0x1e), 'left_down': pelco(0, 0x14, 0x1e, 0x1e),
    'right_up': pelco(0, 0x0a, 0x1e, 0x1e), 'right_down': pelco(0, 0x12, 0x1e, 0x1e),
    'stop': pelco(0, 0, 0, 0),
    'zoomtele': pelco(0, 0x20, 0x1e, 0x1e), 'zoomwide': pelco(0, 0x40, 0x1e, 0x1e),
    'FocusNearAutoOff': pelco(0x01, 0, 0x30, 0x30), 'FocusFarAutoOff': pelco(0, 0x80, 0x30, 0x30),
    'IrisOpenAutoOff': pelco(0x02, 0, 0x30, 0x30), 'IrisCloseAutoOff': pelco(0x04, 0, 0x30, 0x30),
}
for verb, frame in want.items():
    check(f'{verb} -> Pelco-D', ptz(e, verb), [frame])
check('callpreset 5', ptz(e, 'callpreset', preset=5), [pelco(0, 0x07, 0, 5)])
check('speed levels 0..10 -> 5..55, others 30',
      [int(ptz(e, 'right', speed=s)[0].split()[4], 16) for s in (0, 1, 5, 10, 11, 32)], [5, 10, 30, 55, 30, 30])

# --- the _MY customer build wraps the same Pelco-D in a 0x51 envelope -----------
e = make([CUST_MY])
check('_MY wraps zoomtele', ptz(e, 'zoomtele'), [wrap(0x18, bytes.fromhex(pelco(0, 0x20, 0x1e, 0x1e)))])
check('_MY wraps setpreset', ptz(e, 'setpreset', preset=5), [wrap(0x18, bytes.fromhex(pelco(0, 0x03, 0, 5)))])

# --- af_protocol_5 does not change the PTZ verbs --------------------------------
e = make([AF_PROTO5])
check('af_protocol_5 zoomwide still plain Pelco-D', ptz(e, 'zoomwide'), [pelco(0, 0x40, 0x1e, 0x1e)])

# --- AF data and detection boxes from media_server go out unchanged ---------------
e = make()
v2 = bytes.fromhex('51010478011112340506024000110000640000')[:17]
v2 += bytes([sum(v2) & 0xff])
check('aftrans payload written verbatim', ptz(e, 'aftrans', data=v2), [v2.hex(' ')])
box = bytes.fromhex('ff019100204010205a')
cfg_send_coord = 0x70ea8 + 6786          # AfConfig bSendCoordinate in the PTZ config block
e.uc.mem_write(cfg_send_coord, struct.pack('<h', 1))
check('Coordinatetrans written verbatim when bSendCoordinate', ptz(e, 'Coordinatetrans', data=box), [box.hex(' ')])

# --- version query (Get_AF_Version) ---------------------------------------------
e = make()
board(e, bytes([0x56, 0x45, 0x52, 0x06, 0x01, 0x20, 0x24, 0x05, 0x17, 0, 0]))
out = e.alloc(256)
r = e.call(GET_AF_VERSION, out)
check('VER query frames', [b.hex(' ') for _, b in e.uart], ['45 4e 44 d7'] * 8 + ['56 45 52 ed'])
check('VER reply decoded', (r, e.cstr(out)), (0, b'VER:YUT-MS1134/2.7-13.5mm/800W CameraLens/ TIME:2024-5-17'))

e = make()
body = b'EXVER' + bytes([12]) + b'AF-V2.1 0517'
board(e, body + bytes([sum(body) & 0xff]))
out = e.alloc(256)
r = e.call(GET_AF_VERSION_EX, out)
check('EXVER query frames', [b.hex(' ') for _, b in e.uart][-1], '45 58 56 45 52 8a')
check('EXVER reply decoded', (r, e.cstr(out)), (0, b'AF-V2.1 0517'))
e = make()
board(e, body + bytes([(sum(body) + 1) & 0xff]))
check('EXVER bad checksum refused', e.call(GET_AF_VERSION_EX, e.alloc(256)), 0xffffffff)

# --- firmware upgrade over the same port (ttl_upgrade_proc_public) ---------------
FW = bytes((i * 7 + 3) & 0xff for i in range(300))
e = make()
e.overrides['open64'] = lambda *a: 7
sent, inbox, polls = [], bytearray(), [0]


def req(addr):
    f = b'DATA' + struct.pack('>I', addr) + b'\x80'
    return f + bytes([sum(f) & 0xff])


def write(fd, buf, n, *_):
    b = bytes(e.uc.mem_read(buf, n))
    sent.append(b)
    if b.startswith(b'START'):
        inbox.extend(req(0))
    elif b.startswith(b'DATA'):
        nxt = struct.unpack('>I', b[4:8])[0] + 128
        inbox.extend(req(nxt) if nxt < len(FW) else b'OK\x9a')
    return n


def select(*_):
    polls[0] += 1
    if polls[0] > 50:
        raise SystemExit('upgrade emulation stuck')
    return 1 if inbox else 0


def read(fd, buf, n, *_):
    b = bytes(inbox[:n])
    del inbox[:n]
    e.uc.mem_write(buf, b)
    return len(b)


e.overrides.update(write=write, select=select, read=read, fopen64=lambda *a: 0x1000,
                   ftell=lambda *a: len(FW), fseek=lambda *a: 0, fclose=lambda *a: 0,
                   read_file_to_buffer=lambda p, buf, n, *_: (e.uc.mem_write(buf, FW[:n]), len(FW[:n]))[1])
r = e.call(TTL_UPGRADE, e.alloc(32, b'/tmp/upguard_af.bin\0'), count=50_000_000)
start = b'START' + struct.pack('>I', len(FW))
blocks = [b for b in sent if b.startswith(b'DATA')]
check('upgrade wakes the board with END x15', sent[:15], [b'END\xd7'] * 15)
check('upgrade START frame', sent[15], start + bytes([sum(start) & 0xff]))
check('upgrade block addresses', [struct.unpack('>I', b[4:8])[0] for b in blocks], [0, 128, 256])
check('upgrade block layout', {(len(b), b[8], sum(b[:137]) & 0xff == b[137]) for b in blocks}, {(138, 0x80, True)})
check('upgrade payload', b''.join(b[9:137] for b in blocks)[:len(FW)], FW)
check('upgrade ends on OK', r, 0)

# --- AF data frames built by media_server's CAfV1..CAfV6 --------------------------
# The ISP calls are replaced by fakes with known values; each frame is compared
# with an independent encoder of the layout AF-BOARD-PROTOCOL.md gives.
MS = f'{ROOT}/rootfs/opt/ch/media_server'
MS_PLT = plt_map(MS)
random_cells = {(a, w): (0x9e3779b1 * (a * 16 + w + 1)) % (1 << 36) | (1 << 20) for a in range(5) for w in range(16)}
STATS = bytearray(512)
for (a, w), v in random_cells.items():
    STATS[a * 80 + w * 5:a * 80 + w * 5 + 5] = v.to_bytes(5, 'little')
GAIN, NIGHT, IRCUT, IRCUT_EXTRA, IR_PCT, WHITE_PCT = 37.9, True, 2, 1, 55, 66


def sender(vfunc, cfg_type, width=2960):
    e = Emu(MS, MS_PLT, product=0x681)
    e.w32(0x2a2344, 0x681)                                   # product type, as main() caches it
    obj = e.alloc(256)
    e.w32(obj + 8, cfg_type)
    e.w32(obj + 96, 1)                                       # thread running
    frames = []
    e.fake(0x4db74, lambda *a: 0)                            # AF window setup (MI_ISP)
    e.fake(0x2032c8, lambda p, *a: (e.w32(p, 9), 0)[1])      # open ISP frame-sync fd
    e.fake(0x2032ec, lambda *a: 1)                           # wait for a frame
    e.fake(0x2032e0, lambda *a: 0)
    e.fake(0x1fad50, lambda r0, r1, buf, *a: e.uc.mem_write(buf, bytes(STATS)) or 0)  # AF statistics
    e.fake(0x4f550, lambda pw, ph, *a: (e.w32(pw, width), e.w32(ph, 1666), 0)[2])    # main stream size
    e.fake(0x4f584, lambda *a: GAIN)                         # sensor gain x ISP gain
    e.fake(0x4f5e8, lambda *a: 0 if NIGHT else 1)            # 1 = day
    e.fake(0x4f618, lambda *a: 1 if NIGHT else 0)            # V6: night or lamp on
    e.fake(0x4f364, lambda *a: IRCUT)                        # IR-cut mode setting
    e.fake(0x4f370, lambda *a: IRCUT_EXTRA)
    e.fake(0x4f5b8, lambda *a: IR_PCT)
    e.fake(0x4f5d0, lambda *a: WHITE_PCT)
    e.fake(0xe5cd4, lambda *a: 7)

    def aux(m, *_):
        frames.append(bytes(e.uc.mem_read(m + 4, e.r32(m))))
        e.w32(obj + 96, 0)                                   # one frame is enough
        return 0
    e.overrides['AuxMsgPTZCmdAfData'] = aux
    e.call(vfunc, obj, count=20_000_000)
    return frames


def cell(a, w):
    return random_cells[(a, w)]


def fv(arrays, w, shift):
    v = sum(cell(a, w) >> 6 for a in arrays)
    return [(v >> (shift + 8)) & 0xff, (v >> shift) & 0xff]


def mid16(a, w):
    v = cell(a, w)
    return [(v >> 16) & 0xff, (v >> 8) & 0xff]


def framed(body):
    return bytes(body) + bytes([sum(body) & 0xff])


SHARP = (0, 1, 3, 4)                     # the four sharpness arrays; array 2 (luma) is skipped
g, night = int(GAIN), int(NIGHT)
res_class = 4                            # width 2960: >= 2592
want = {
    'CAfV1 (type 0)': (0x4d640, 0, framed([0x51, 1, 4, 0x78, 1, 0x0d] + fv(SHARP, 0, 3) + fv(SHARP, 1, 3)
                                          + [g, night, IRCUT])),
    'CAfV2 (type 1)': (0x4e1c4, 1, framed([0x51, 1, 4, 0x78, 1, 0x11] + fv(SHARP, 0, 3) + fv(SHARP, 1, 3)
                                          + [g, res_class << 4 | night] + mid16(0, 1)
                                          + [IRCUT, IR_PCT, WHITE_PCT])),
    'CAfV3 (type 2)': (0x4cfec, 2, framed([0x51, 1, 4, 0x78, 1, 0x0d] + fv(SHARP, 0, 3) + fv(SHARP, 1, 3)
                                          + [g, night, IRCUT, IR_PCT, WHITE_PCT])),
    'CAfV4 (type 3)': (0x4dea8, 3, framed([0x51, 1, 4, 0x78, 1, 0x0d] + fv(SHARP, 0, 3) + fv(SHARP, 1, 3)
                                          + [g, night, IRCUT | IRCUT_EXTRA << 4, IR_PCT, WHITE_PCT])),
    'CAfV6 (_MY)': (0x4d2a8, 6, framed([0x51, 1, 4, 0x79, 0x19, 9] + fv((0, 1), 0, 2) + fv((0, 1), 1, 2)
                                       + [g, night, IRCUT | IRCUT_EXTRA << 4, IR_PCT, WHITE_PCT])),
}
for name, (vf, t, frame) in want.items():
    check(f'{name} AF frame', sender(vf, t), [frame])
check('CAfV2 resolution class from stream width', [sender(0x4e1c4, 1, w)[0][11] >> 4 for w in (720, 1280, 1920, 2560, 3840)],
      [4, 0, 1, 3, 6])
v5 = sender(0x4cb64, 4)[0]
check('CAfV5 (type 4) FC frame layout', (v5[:4], list(v5[4:8]), len(v5), v5[14] == sum(v5[:14]) & 0xff, v5[15]),
      (bytes.fromhex('fc141a0a'), mid16(1, 1) + mid16(0, 1), 16, True, 0))

print(f'{failures} failure(s)' if failures else 'lens board protocol: all checks passed')
sys.exit(1 if failures else 0)

builder/Dockerfile

new, 9 lines. The Ubuntu 24.04 build container (openipc-builder:24.04).

FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential bc bison flex cpio rsync unzip wget curl file python3 git \
    libncurses-dev xz-utils bzip2 lzop ca-certificates cmake gawk libssl-dev \
    u-boot-tools whiptail patch perl locales bsdextrautils && \
    sed -i 's/# en_US.UTF-8/en_US.UTF-8/' /etc/locale.gen && locale-gen && \
    rm -rf /var/lib/apt/lists/*
ENV LANG=en_US.UTF-8