MC-L18D OpenIPC port: notes, RE tools, image, upstream submodules + patches
Track the OpenIPC trees (firmware, sensors, linux, ipctool, majestic-af) and onvif_simple_server as submodules pinned to their upstream commits. The port's changes to each live in patches/<submodule>.patch, generated by patches/export.sh from the submodules' uncommitted work. README.md walks through the reverse engineering and bring-up, step by step. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EfVNki7giKruPunvux6dDA
This commit is contained in:
commit
61168c0021
31 files changed
+17153
No files matched your search
@@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
[submodule "linux-infinity6c"]
|
||||
path = linux-infinity6c
|
||||
url = https://github.com/OpenIPC/linux.git
|
||||
branch = sigmastar-infinity6c
|
||||
[submodule "firmware"]
|
||||
path = firmware
|
||||
url = https://github.com/OpenIPC/firmware.git
|
||||
[submodule "sensors"]
|
||||
path = sensors
|
||||
url = https://github.com/OpenIPC/sensors.git
|
||||
[submodule "ipctool"]
|
||||
path = ipctool
|
||||
url = https://github.com/OpenIPC/ipctool.git
|
||||
[submodule "majestic-af"]
|
||||
path = majestic-af
|
||||
url = https://github.com/OpenIPC/majestic-af.git
|
||||
[submodule "onvif_simple_server"]
|
||||
path = onvif_simple_server
|
||||
url = https://github.com/roleoroleo/onvif_simple_server.git
|
||||
@@ -0,0 +1,280 @@
|
||||
# MC-L18D lens board (AF / zoom) serial protocol
|
||||
|
||||
Decoded from the vendor `comm_server` and `media_server` in
|
||||
`backup-ssc377d-nor16m.bin` (app V3.4.5.2, built 2025-11-06). The method was
|
||||
static disassembly plus running the vendor's own code in an ARM emulator.
|
||||
`af-board-re/verify.py` re-derives every frame below from the binaries: 40 checks,
|
||||
all passing. Nothing here was observed on a real board. The board's side is
|
||||
inferred from what the camera sends and what it accepts back.
|
||||
|
||||
This replaces the earlier note in `MCL18D-PORT.md` ("115200 baud, `FC 01`
|
||||
protocol"). That note was wrong for this camera. The `FC` frames belong to
|
||||
`af_protocol_5_flag` builds and to other products. The 115200-baud `0x51`
|
||||
channel is the `_MY` customer's upgrade port on `/dev/ttyS4`. Both are listed
|
||||
under "Other variants" below.
|
||||
|
||||
## Link
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Port | `/dev/ttyS2` (FUART, connector D7 TX/RX), the same port as a Pelco pan/tilt head |
|
||||
| Line | 57600 8N1, used whenever `/opt/ch/af.flag` exists. This overrides `PTZConfig BaudRate` (2400). `_WTD` customer builds use 115200. A number in `/opt/ch/diy_baudrate` overrides both. |
|
||||
| Direction | Both ways. The camera streams AF data and Pelco-D to the board; the board sends its own `51 01 04 78` status frames back, and the vendor's `media_server` reads them (`thread_af_console_data`). An earlier version of this table said the camera never reads the port; that was wrong. |
|
||||
|
||||
One wire carries four kinds of traffic:
|
||||
|
||||
1. Pelco-D commands for zoom, focus, iris, presets and pan/tilt.
|
||||
2. AF data frames, one per ISP frame, carrying focus values computed from the ISP's AF statistics.
|
||||
3. Detection-box frames, forwarded unchanged.
|
||||
4. A version query at boot, and the firmware upgrade.
|
||||
|
||||
## What this camera is set to
|
||||
|
||||
| Setting | Value on the device | Effect |
|
||||
|---|---|---|
|
||||
| `/opt/ch/af.flag` | present | lens board on ttyS2 at 57600, version query at boot |
|
||||
| `/opt/ch/af_protocol_5_flag` | absent | AF data in the `0x51` format, not `FC` |
|
||||
| customer (`/etc/filesys.ver`, `/etc/flag.customize`) | `_ASKP` | no `_MY` / `_WTD` / `_TV` variant |
|
||||
| product type | 0x681 | no product-specific gain scaling |
|
||||
| `AfConfig type` (`/mnt/nand/config.xml`) | 1 | AF frames from `CAfV2` (18 bytes) |
|
||||
| `AfConfig type` (factory `config.default.mcl18d.xml`) | 2 | AF frames from `CAfV3` (16 bytes) |
|
||||
| `AfConfig bSendOnStart` | 1 | AF frames are always forwarded |
|
||||
| `AfConfig bSendCoordinate`, `/opt/ch/send_hd_coordinate.flag` | 1, present | detection boxes are forwarded |
|
||||
|
||||
`AfConfig type` selects the sender: 0 → V1, 1 → V2, 2 → V3, 3 → V4, 4 → V5,
|
||||
anything else → V1. Three things override it:
|
||||
- `/opt/ch/diy_afconfigN` (N = 1–6) selects VN directly.
|
||||
- The `_MY` customer forces V6.
|
||||
- `flag.tv.af5.version`, `flag.af.ptz.wtd`, or the `_TV` customer on product 1538 force V5.
|
||||
|
||||
## 1. Commands: Pelco-D
|
||||
|
||||
`FF addr b2 b3 d1 d2 sum`: address 1, and `sum` is the sum of bytes 1–5. The
|
||||
board takes standard Pelco-D, and the vendor sends it unwrapped.
|
||||
|
||||
| Verb (web / ONVIF / CGI) | Frame |
|
||||
|---|---|
|
||||
| zoom tele / wide | `FF 01 00 20 ss ss cs` / `FF 01 00 40 ss ss cs` |
|
||||
| focus near / far (`FocusNearAutoOff` / `FocusFarAutoOff`) | `FF 01 01 00 30 30 62` / `FF 01 00 80 30 30 E1` |
|
||||
| iris open / close (`IrisOpenAutoOff` / `IrisCloseAutoOff`) | `FF 01 02 00 30 30 63` / `FF 01 04 00 30 30 65` |
|
||||
| stop | `FF 01 00 00 00 00 01` |
|
||||
| up / down / left / right | `FF 01 00 08 00 ss` / `00 10 00 ss` / `00 04 ss 00` / `00 02 ss 00` (+ sum) |
|
||||
| diagonals | `0C` / `14` / `0A` / `12` with both speeds |
|
||||
| goto / set / clear preset n | `FF 01 00 07 00 nn` / `00 03 00 nn` / `00 05 00 nn` (+ sum) |
|
||||
|
||||
- **Speed `ss`:** the request's speed level 0–10 maps to 0x05–0x37 in steps of 5. Any other value gives 0x1E.
|
||||
- **Zoom:** zoom frames carry the pan/tilt speed in both data bytes.
|
||||
- **Focus and iris:** these always use 0x30.
|
||||
- **Bare `focusnear` / `focusfar`:** these verbs send the stop frame. The web page and CGI only ever send the `…AutoOff` forms.
|
||||
|
||||
## 2. AF data: camera to board
|
||||
|
||||
`media_server` waits for each ISP frame, with a 500 ms timeout, and reads the
|
||||
AF statistics. It builds one frame from them and sends it to `comm_server`,
|
||||
which writes it to the port unchanged. At 30 fps that is about 30 frames a second.
|
||||
|
||||
`comm_server` writes a frame only if it is longer than 3 bytes and one of these holds:
|
||||
- `bSendOnStart` is set, or
|
||||
- the last PTZ command was under 300 s ago and the customer is not `_Y_`.
|
||||
|
||||
`/opt/ch/flag.af.init.disable` holds frames back until the first PTZ move.
|
||||
|
||||
### Focus values
|
||||
|
||||
The ISP AF statistics are five arrays of 16 windows. Each value is 40 bits,
|
||||
little-endian, so each array is 80 bytes. The senders add arrays 0, 1, 3 and 4
|
||||
and skip array 2. That fits the SigmaStar layout high-IIR, low-IIR, luma,
|
||||
vertical FIR, horizontal FIR, but the names are inferred from the layout.
|
||||
|
||||
- FV(w) = Σ over arrays {0,1,3,4} of (stat[a][w] >> 6)
|
||||
- Sent as two bytes: `(FV >> 11) & FF`, then `(FV >> 3) & FF`. That is FV/8 as a 16-bit big-endian value, truncated.
|
||||
- Window 0 covers (19,19)–(1003,1003) of the 0–1023 normalised frame, almost the whole picture.
|
||||
- Window 1 covers (170,170)–(850,850), the central two-thirds. For `type 3` it is (334,334)–(668,668).
|
||||
- So FV0 is whole-frame sharpness and FV1 is centre sharpness.
|
||||
|
||||
### CAfV2: this camera's live setting, 18 bytes
|
||||
|
||||
| Byte | Content |
|
||||
|---|---|
|
||||
| 0–5 | `51 01 04 78 01 11` |
|
||||
| 6–7 | FV window 0 |
|
||||
| 8–9 | FV window 1 |
|
||||
| 10 | total gain, (sensor gain / 1024) × (ISP gain / 1024), truncated to an integer |
|
||||
| 11 | bits 7–4: main-stream width class, where ≥4000 → 7, ≥3840 → 6, ≥3072 → 5, ≥2592 → 4, ≥2560 → 3, ≥2304 → 2, ≥1920 → 1, ≥1080 → 0, smaller → 4. Bit 0 is 1 at night. |
|
||||
| 12–13 | bits 23–16, then 15–8, of stat[0][window 1] (raw) |
|
||||
| 14 | IR-cut mode setting (the `STREAM_FEATURE_IRCUT` mode) |
|
||||
| 15 | IR lamp brightness, % |
|
||||
| 16 | white lamp brightness, % |
|
||||
| 17 | sum of bytes 0–16 |
|
||||
|
||||
### CAfV3: factory default, 16 bytes
|
||||
|
||||
`51 01 04 78 01 0D`, FV0 (2 bytes), FV1 (2 bytes), then:
|
||||
- gain (divided by 30 on product types 1566, 1569, 1698–1700 and 1921; not this camera)
|
||||
- night (1 or 0)
|
||||
- IR-cut mode
|
||||
- IR lamp %
|
||||
- white lamp %
|
||||
- sum
|
||||
|
||||
### Other senders
|
||||
|
||||
| Sender | Length | Layout |
|
||||
|---|---|---|
|
||||
| V1 | 14 | `51 01 04 78 01 0D`, FV0, FV1, gain, night, IR-cut mode, sum |
|
||||
| V4 | 16 | as V3, but the IR-cut byte is mode \| (second IR-cut field << 4) |
|
||||
| V6 (`_MY`) | 16 | `51 01 04 79 19 09`, then FV0' and FV1' (arrays 0 and 1 only, sent as FV >> 10, FV >> 2), gain, night-or-lamp-on, IR-cut byte as in V4, IR %, white %, sum |
|
||||
| V5 (`FC`) | 16 | `FC 14 1A 0A`, then bits 23–8 of stat[1][1], bits 23–8 of stat[0][1], four status bytes from globals I did not identify, 2 or 5, the sum of bytes 0–13, and `00` |
|
||||
|
||||
Bytes 4 and 5 of the `0x51` frames are not a length. V1 and V3 both say `0D`
|
||||
but are 14 and 16 bytes long. Treat bytes 0–5 as a fixed header per sender.
|
||||
|
||||
## 3. Detection boxes: camera to board
|
||||
|
||||
When `bSendCoordinate` is set, `comm_server` writes `media_server`'s
|
||||
"Coordinatetrans" payloads unchanged. I saw two record formats:
|
||||
- **9-byte records:** `FF 01 91 00 x y w h ..`
|
||||
- **7-byte records:** `FF 01 C5 …`, with `C2` on `_WTD` and `tv.af5` builds. The coordinates are scaled to 800 × 480.
|
||||
|
||||
These look like human-detection boxes for auto-tracking heads. I have not
|
||||
decoded them fully.
|
||||
|
||||
## 4. Version query at boot
|
||||
|
||||
`thread_ptz` runs this every time it starts with `af.flag` set, retrying up to three times until it gets an answer.
|
||||
The result goes into `/tmp/AF_version.txt` and is shown in the app. The ASCII
|
||||
commands end in the sum of their characters.
|
||||
|
||||
**Camera sends:** `END` + `D7` eight times, 60 ms apart, then `VER` + `ED`.
|
||||
**Board replies** with up to 11 bytes. The camera waits 100 ms, then reads with a 1 s `select()`, tried twice:
|
||||
|
||||
| Byte | Content |
|
||||
|---|---|
|
||||
| 0–2 | not checked (probably `VER`) |
|
||||
| 3 | lens model, see below. Any other value fails, and the camera tries `EXVER`. |
|
||||
| 4 | variant: for model 6, 0 is MX3901 and 1 is MS1134 |
|
||||
| 5–6 | year, BCD (`20 24`) |
|
||||
| 7 | month, BCD |
|
||||
| 8 | day, BCD |
|
||||
| 9–10 | not checked |
|
||||
|
||||
| Code | Lens |
|
||||
|---|---|
|
||||
| 01 / 02 | YUT-MX3901 2.7-13.5mm 200W / 2.8-12mm 200W |
|
||||
| 03 / 04 | FTK-MX3901 2.8-12mm 300W / 500W |
|
||||
| 05 | YUT-MX3901 2.7-13.5mm 500W |
|
||||
| 06 | YUT-MX3901 (or MS1134) 2.7-13.5mm 800W |
|
||||
| 07 / 08 | YUT-MX3901 2.8-8mm 400W / 500W |
|
||||
| 09 | YUT-MX3901 6-22mm 300W |
|
||||
| 10 / 11 | YUT-MX3901 5-50mm 200W / FTK-MX3901 6-22mm 500W |
|
||||
| 12 / 13 | YUT-MX3901 3.6-11mm 4K / FH-MX3901 3.3-10mm |
|
||||
| 14 / 15 | YUT-MX3901 2.7-12mm 500W / 2.8-8mm 800W |
|
||||
| 20 / 21 | pan/tilt boards "PTZ- MODEL-020" / "PTZ - MODEL-021" |
|
||||
|
||||
**Fallback, `EXVER`:** the camera sends `END` + `D7` eight times, then
|
||||
`EXVER` + `8A`. The board replies `EXVER`, a count n, n bytes of text, and the
|
||||
sum of all the bytes before it. The text is the version string.
|
||||
|
||||
## 5. Firmware upgrade: same port, same speed
|
||||
|
||||
This is `ttl_upgrade_proc_public`, used when the app pushes a lens-board
|
||||
image (`/tmp/upguard_af.bin`; the image names refer to an HK32 MCU). The board
|
||||
pulls the image in 128-byte blocks by address:
|
||||
|
||||
| Step | Direction | Bytes |
|
||||
|---|---|---|
|
||||
| wake | camera to board | `END` + `D7` fifteen times, 60 ms apart |
|
||||
| start | camera to board | `START` + size as a 32-bit big-endian value + sum (10 bytes) |
|
||||
| request | board to camera | `DATA` + address as a 32-bit big-endian value + `80` + sum (10 bytes). The first one is `44 41 54 41 00 00 00 00 80 9A`. |
|
||||
| block | camera to board | `DATA` + the same address + `80` + 128 bytes of image (the last block zero-padded) + the sum of bytes 0–136 (138 bytes) |
|
||||
| done | board to camera | `OK` + `9A` |
|
||||
|
||||
If the next request does not advance the address by 128, the camera resends
|
||||
the previous block. Do not try this without the vendor image and a way to
|
||||
recover the board.
|
||||
|
||||
## Other variants in this comm_server (not this camera)
|
||||
|
||||
- **`_MY` customers:** Pelco-D is wrapped as `51 01 04 79 18 07` + the 7 Pelco bytes + the sum of all prior bytes, 14 bytes in total. Upgrades go through a separate envelope at 115200 on `/dev/ttyS4`:
|
||||
- frame: `51 01 04 79 <target> <len> <payload> <sum>`
|
||||
- target, from the image name: `AF` 0x78, `PTZ` 0x77, `PWR` 0x76, `BTL` 0x01
|
||||
- data packet payload: `84 11`, packet number as big-endian 16-bit, then data
|
||||
- board replies use the same envelope, and the camera checks header, length and sum
|
||||
- **`FC 01 A3 01 00 A1`:** sent with `echo` to ttyS2 on product types 1813, 1817 and 1825 only.
|
||||
- **`FC 01 B4 02 00 00 B3` and `FC 01 B4 02 00 01 B4`:** toggled by an alarm-light handler.
|
||||
- **`FF 01 00 A0 00 F1 92`:** a status query for `_WTD` heads.
|
||||
|
||||
## What this means for OpenIPC
|
||||
|
||||
Observed on the camera, 2026-10-28/29, OpenIPC with the keep-alive below. Every
|
||||
item here is measured, not inferred from the binaries, unless it says otherwise.
|
||||
|
||||
- **The board sleeps without AF data.** Plain Pelco-D on its own does nothing:
|
||||
no pan, tilt, zoom or focus, no reply to the version query, and not a single
|
||||
byte back (`/proc/tty/driver` rx stayed 0 through a sweep of every baud from
|
||||
2400 to 115200, Pelco-D at addresses 0 and 1, and Pelco-P). Five CAfV2 frames
|
||||
33 ms apart wake it; one does not. Once awake it obeyed a plain Pelco-D frame
|
||||
3 s after the last AF frame, and had gone back to sleep 40 s after. A frame
|
||||
every 100 ms kept it awake through every test. The vendor never sees this
|
||||
because it streams a frame per video frame from boot.
|
||||
- **Waking takes about 20 s.** The first stream after sleep starts a run of
|
||||
large focus moves (a homing pass, INFERRED from the picture) before it settles.
|
||||
- **The pan/tilt is behind the board.** Pan and tilt answer only while the board
|
||||
is awake, at the same 57600 and address 1, so they share its gate.
|
||||
- **`pelco-ptz keepalive`** sends `pelco_af_frame()` every `keepalive_ms`
|
||||
(default 100) and `S94mcl18d` starts it at boot. Its values are constant, so
|
||||
the board's own autofocus has nothing real to climb; focus after a zoom is not
|
||||
managed. Commands from `pelco-ptz` go out between its frames.
|
||||
- **No absolute positions, no feedback.** The head ignores Pelco-D set-position
|
||||
(0x4B/0x4D/0x4F, also after 0x49 "set zero") and never answers the position
|
||||
queries (0x51/0x53/0x55). Its presets work: set, move away, go to returns to
|
||||
the stored view. So presets are this head's only absolute positions, and
|
||||
`onvif.conf` no longer offers AbsoluteMove/RelativeMove.
|
||||
- **Board status frames.** While something moves the board sends
|
||||
`51 01 04 78 01 0a 0a 10 3b 3b NN 21 3b 14 0f 3b <sum>`. `NN` rose 02 to 03 on
|
||||
zoom-in and fell to 01 on zoom-out, so it looks like a coarse zoom step
|
||||
(INFERRED). Nothing in them changed with pan or tilt, and the board is silent
|
||||
while idle.
|
||||
- **`mcl18d-af`** still ships but is not part of the fix. It needs the
|
||||
keep-alive like everything else, majestic on this platform refuses its
|
||||
`?crop=` (HTTP 501, so it judges the whole frame), and the board's own focus
|
||||
moves under it. It has not given a good result on the camera.
|
||||
- **Termios.** The vendor's version query clears CREAD and still gets its reply
|
||||
because the vendor kernel ignores CREAD. OpenIPC's `ms_uart.c` honours it, so a
|
||||
reader here must set CREAD (`pelco-ptz` does).
|
||||
- **Shared port.** The whole port runs at 57600 when `af.flag` is set, so a
|
||||
separate Pelco head on the same wires would have to run at 57600 too.
|
||||
|
||||
## Reproducing
|
||||
|
||||
```sh
|
||||
cd af-board-re
|
||||
python3 -m pip install unicorn # in a venv
|
||||
python3 verify.py # defaults to ../../flash_dump_ssc377d
|
||||
python3 od.py ../../flash_dump_ssc377d/rootfs/opt/ch/comm_server 1bd64 1c1e0 # annotated disassembly
|
||||
```
|
||||
|
||||
Addresses for the flash-dump build:
|
||||
|
||||
**comm_server:**
|
||||
|
||||
| Function | Address |
|
||||
|---|---|
|
||||
| `HandleYuntai` (after its upgrade guard) | 0x43408 |
|
||||
| `Get_AF_Version` | 0x1bd64 |
|
||||
| `Get_AF_Version_EX` | 0x1b8a8 |
|
||||
| `ttl_upgrade_proc_public` | 0x1c270 |
|
||||
| `PtzInitComm` | 0x3b4f8 |
|
||||
| `thread_ptz` | 0x3bed8 |
|
||||
|
||||
**media_server:**
|
||||
|
||||
| Function | Address |
|
||||
|---|---|
|
||||
| `InitAf` | 0x429a4 |
|
||||
| `CAfV1` | 0x4d640 |
|
||||
| `CAfV2` | 0x4e1c4 / 0x4dfcc |
|
||||
| `CAfV3` | 0x4cfec / 0x4cde0 |
|
||||
| `CAfV4` | 0x4dea8 |
|
||||
| `CAfV5` | 0x4cb64 |
|
||||
| `CAfV6` | 0x4d2a8 |
|
||||
+5257
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,855 @@
|
||||
# Porting the AnjoyVision MC-L18D to OpenIPC: everything learned, and where it came from
|
||||
|
||||
This guide is for learning. It covers how the vendor firmware was taken apart, where
|
||||
each hardware fact came from, every file I added or changed and why, how each piece was
|
||||
tested, and the mistakes I made and corrected along the way.
|
||||
|
||||
Two companion files go deeper on single topics:
|
||||
- `MCL18D-PORT.md`: the short port notes.
|
||||
- `AF-BOARD-PROTOCOL.md`: the lens-board protocol, byte by byte.
|
||||
|
||||
> **Status:** sections 1–19 were written before the camera was on the bench. Every claim in them is backed by one of these:
|
||||
> - the vendor binaries;
|
||||
> - OpenIPC's sources;
|
||||
> - a build that succeeded;
|
||||
> - a test against a simulation.
|
||||
>
|
||||
> Section 20 is what the camera then showed, 2026-10-28/29, and where it corrected the earlier sections they have been updated. Section 14 lists what was still to be checked then.
|
||||
|
||||
---
|
||||
|
||||
## Contents
|
||||
|
||||
1. [What you started with](#1-what-you-started-with)
|
||||
2. [How OpenIPC builds an image (the mental model)](#2-how-openipc-builds-an-image-the-mental-model)
|
||||
3. [Taking the vendor firmware apart](#3-taking-the-vendor-firmware-apart)
|
||||
4. [Hardware facts and their sources](#4-hardware-facts-and-their-sources)
|
||||
5. [Kernel: the device tree](#5-kernel-the-device-tree)
|
||||
6. [The GC5603 sensor driver](#6-the-gc5603-sensor-driver)
|
||||
7. [Registering the board in the OpenIPC tree](#7-registering-the-board-in-the-openipc-tree)
|
||||
8. [The board package `anjvision-mcl18d`](#8-the-board-package-anjvision-mcl18d)
|
||||
9. [PTZ over ONVIF](#9-ptz-over-onvif)
|
||||
10. [The lens board (zoom / focus) protocol](#10-the-lens-board-zoom--focus-protocol)
|
||||
11. [Manual focus, iris and `mcl18d-af`](#11-manual-focus-iris-and-mcl18d-af)
|
||||
12. [Building](#12-building)
|
||||
13. [Testing: what was tested and how](#13-testing-what-was-tested-and-how)
|
||||
14. [Not verified on hardware: first-boot checklist](#14-not-verified-on-hardware-first-boot-checklist)
|
||||
15. [Upstreaming: what OpenIPC would and would not accept](#15-upstreaming-what-openipc-would-and-would-not-accept)
|
||||
16. [Every file changed, by repository](#16-every-file-changed-by-repository)
|
||||
17. [Mistakes made and corrected](#17-mistakes-made-and-corrected)
|
||||
18. [Loose ends in the folder](#18-loose-ends-in-the-folder)
|
||||
19. [Techniques worth reusing](#19-techniques-worth-reusing)
|
||||
20. [On the hardware: bring-up, 2026-10-28/29](#20-on-the-hardware-bring-up-2026-10-2829)
|
||||
|
||||
---
|
||||
|
||||
## 1. What you started with
|
||||
|
||||
| Item | What it is |
|
||||
|---|---|
|
||||
| `backup-ssc377d-nor16m.bin` | Full 16 MB SPI NOR dump of your camera: boot, kernel, rootfs and settings. Everything authoritative comes from this. |
|
||||
| `r1885__firmware_MCL18D_V0-A-H5_V3.6.1.3_20260917092033.bin` | The vendor's update file. It has a newer app build than your dump, but the same kernel and sensor driver. |
|
||||
| `MC-L18D-spec-sheet-EN.pdf`, `MC-L18D-wiring-diagram-EN.pdf` | Connector pinouts (D1, D5, D6, D7) and the feature list. |
|
||||
|
||||
**The hardware:**
|
||||
- SoC: SigmaStar SSC377D, the "Infinity6C" family.
|
||||
- Sensor: GalaxyCore GC5603.
|
||||
- Flash: 16 MB NOR.
|
||||
- Board layout: a copy of SigmaStar's SSC027A-S01A reference design.
|
||||
|
||||
**Optional external boards** hang off connector D7:
|
||||
- an autofocus/zoom lens board;
|
||||
- a Pelco-D pan/tilt head.
|
||||
|
||||
---
|
||||
|
||||
## 2. How OpenIPC builds an image (the mental model)
|
||||
|
||||
You need this picture before any of the changes make sense.
|
||||
|
||||
- **OpenIPC firmware is a Buildroot "external tree".**
|
||||
- `make BOARD=x` picks `br-ext-chip-<vendor>/configs/x_defconfig`.
|
||||
- That defconfig is merged with `general/openipc.fragment`.
|
||||
- Buildroot then builds the toolchain, kernel, packages and root filesystem.
|
||||
- **The kernel** is not in the firmware repo.
|
||||
- It is downloaded as a tarball from **OpenIPC/linux**, branch `sigmastar-infinity6c` for this chip.
|
||||
- The kernel config file lives in the firmware repo, under `br-ext-chip-sigmastar/board/infinity6c/`.
|
||||
- **SigmaStar's device tree** is chosen by a kernel config option, `CONFIG_SS_DTB_NAME`, not by U-Boot.
|
||||
- A new board therefore needs a new `.dts` plus a kernel config copy pointing at it.
|
||||
- **Sensor drivers** are separate kernel modules (`sensor_<name>_mipi.ko`).
|
||||
- They are built from **OpenIPC/sensors** by the `sigmastar-osdrv-sensors` package.
|
||||
- At boot, `load_sigmastar` (from the `sigmastar-osdrv-infinity6c` package) `insmod`s the driver named in the U-Boot variable `sensor`.
|
||||
- The defconfig's `BR2_OPENIPC_SNS_MODEL` sets that default.
|
||||
- **The ISP needs an IQ (image tuning) file** per sensor: `/etc/sensors/<sensor>.bin`.
|
||||
- **majestic** is the closed-source streamer (RTSP, web UI, night mode, ONVIF). It reads `/etc/majestic.yaml`. You change that with the `cli` tool: `cli -s .key value` / `cli -g .key`.
|
||||
- **Per-board settings** go through sanctioned hooks, not shared files. `S30customizer` runs these on first boot:
|
||||
- `/usr/share/openipc/customizer.sh`
|
||||
- `/usr/share/openipc/muxes.sh`
|
||||
|
||||
`firstboot` (a factory reset) makes them run again.
|
||||
- **Shipped shell scripts are comment-stripped** at build time (`general/scripts/strip-shell-comments.awk`). They run under **busybox `ash`**, not bash.
|
||||
- **CI rule:** every defconfig and package must be either built by CI or listed in `.github/scripts/ci-matrix.py` with a reason. `ci-matrix.py --self-test` enforces this.
|
||||
|
||||
**Source:** `openipc/firmware/CLAUDE.md`, `Makefile`, `general/`, and reading the build as it ran.
|
||||
|
||||
---
|
||||
|
||||
## 3. Taking the vendor firmware apart
|
||||
|
||||
### 3.1 The update file → `firmware_MCL18D_V3.6.1.3/`
|
||||
|
||||
`binwalk` and `xxd` showed three parts:
|
||||
|
||||
| Offset | Size | Content |
|
||||
|---|---|---|
|
||||
| 0 | 1556 | Vendor header: magic `ANJOY888`, model `MCL18D_V0-A-H5_V3.6.1.3`, date 2026-09-17 |
|
||||
| 1556 | 1,899,640 | uImage kernel |
|
||||
| 1,901,196 | 8,897,236 | xz SquashFS root filesystem |
|
||||
| after that | 3372 | Zero padding |
|
||||
|
||||
```sh
|
||||
dd if=update.bin of=kernel.uImage bs=1 skip=1556 count=$((1899576+64))
|
||||
dd if=kernel.uImage of=kernel.xz bs=64 skip=1 # strip the 64-byte uImage header
|
||||
xz -dc kernel.xz > kernel.img # header says lzma; it's really xz
|
||||
dd if=update.bin of=rootfs.squashfs bs=1 skip=1901196 count=8897236
|
||||
unsquashfs -d rootfs rootfs.squashfs
|
||||
```
|
||||
|
||||
**Lesson:** the uImage header claims LZMA but the payload is xz. Trust magic bytes (`FD 37 7A 58 5A`), not headers.
|
||||
|
||||
**The device tree inside the kernel.**
|
||||
1. I searched `kernel.img` for the DTB magic `D0 0D FE ED`. There were five candidates.
|
||||
2. I read each candidate's `totalsize` field and kept the real one, at offset 3,638,064.
|
||||
3. I carved it out and decompiled it:
|
||||
|
||||
```sh
|
||||
dd if=kernel.img of=board.dtb bs=1 skip=3638064
|
||||
dtc -I dtb -O dts -o board.dts board.dtb
|
||||
```
|
||||
|
||||
### 3.2 The full flash dump → `flash_dump_ssc377d/`
|
||||
|
||||
The partition boundaries come from the U-Boot environment in the dump (`strings | grep mtdparts`), which reads `mtdparts=nor0:0x30000(BOOT),0x200000(kernel),0xCD0000(rootfs),0x100000(DATA)`:
|
||||
|
||||
| Partition | Offset | Size | Content |
|
||||
|---|---|---|---|
|
||||
| BOOT | 0x000000 | 192 KB | IPL + U-Boot + environment |
|
||||
| kernel | 0x030000 | 2 MB | uImage, Linux 5.10.61 |
|
||||
| rootfs | 0x230000 | 0xCD0000 | SquashFS, app V3.4.5.2, built 2025-11-06 |
|
||||
| DATA | 0xF00000 | 1 MB | jffs2: runtime settings (`config.xml`) |
|
||||
|
||||
```sh
|
||||
dd if=dump.bin of=kernel.uImage bs=64K skip=3 count=32
|
||||
dd if=dump.bin of=rootfs.squashfs bs=64K skip=35 count=205
|
||||
dd if=dump.bin of=data.jffs2 bs=64K skip=240 count=16
|
||||
jefferson -f -d data data.jffs2 # pip install jefferson
|
||||
```
|
||||
|
||||
**Findings:**
|
||||
- The kernel is byte-identical to the update file's.
|
||||
- The sensor driver `gc5603_MIPI_1125.ko` is identical.
|
||||
- The app build is older.
|
||||
- Your MAC address, from the U-Boot environment, is `F0:00:06:14:73:FF`. **Keep this dump.** It is your only way back.
|
||||
- `config.xml` in DATA gives the live settings:
|
||||
- `AfConfig enable="1" type="1"`
|
||||
- `PTZConfig PELCO_D ComPort=1 BaudRate=2400`
|
||||
- Dzoom max 10
|
||||
|
||||
### 3.3 Where the vendor's logic lives
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `opt/ch/libtools.so` | Board tables, including the GPIO table per device type |
|
||||
| `opt/ch/media_server` | Video, ISP, IR-cut and lamps, and the AF data sender |
|
||||
| `opt/ch/comm_server` | Serial port: PTZ, lens board, upgrade |
|
||||
| `opt/ch/mainctrl`, `record_server` | Misc GPIO (SD power, LEDs) |
|
||||
| `config/modules/…/gc5603_MIPI_1125.ko` | Sensor driver |
|
||||
| `config/iqfile/gc4023_day.bin` / `gc4023_night.bin` | IQ files. There is no GC5603 one. |
|
||||
| `opt/ch/*.flag` | Feature switches, e.g. `af.flag` = lens board fitted |
|
||||
|
||||
**Tools used:**
|
||||
- `strings`, `objdump`, `radare2` for disassembly;
|
||||
- `unicorn` (Python) to run ARM code;
|
||||
- `pyelftools`;
|
||||
- `dtc`, `jefferson`.
|
||||
|
||||
I did not install a decompiler.
|
||||
|
||||
---
|
||||
|
||||
## 4. Hardware facts and their sources
|
||||
|
||||
GPIO numbers are Linux sysfs numbers. On Infinity6C these equal the pad index, and OpenIPC's kernel uses the same numbering. I checked this by comparing both kernels' pad tables.
|
||||
|
||||
| Function | Pin | Where it came from |
|
||||
|---|---|---|
|
||||
| Speaker amp enable | GPIO 12 (PAD_SPI0_DO) | `libtools.so` table `g_io_mcl12d2`, type code 4 |
|
||||
| Reset button | GPIO 60 (PAD_SR_IO00) | same table, type 3 |
|
||||
| Alarm out / red-blue light | GPIO 10 (PAD_SPI0_CK), driven 1 at boot | same table, type 2, init 1 |
|
||||
| Alarm in | GPIO 44 (PAD_FUART_CTS) | same table, type 1 |
|
||||
| Warning light, active low | GPIO 61 (PAD_SR_IO01), driven 1 (off) at boot | same table, type 12; `mainctrl`'s `GetLedBrGpioPort` pulls it low on alarm |
|
||||
| IR-cut A (night) | GPIO 11 (PAD_SPI0_DI) | the vendor kernel's built-in `/dev/irled` driver table |
|
||||
| IR-cut B (day) | GPIO 80 (PAD_SAR_GPIO1) | same driver |
|
||||
| Light board's day/night output (CDSIN): 1 day, 0 night | GPIO 23 (PAD_PM_IRIN) | same driver ("IRDET"); `media_server` reads it as a level in "Passive" mode |
|
||||
| SD power | GPIO 45 (PAD_FUART_RTS) | device tree, `irled` driver, `record_server` |
|
||||
| SD card detect | pad 22 (PAD_PM_SD_CDZ) | device tree |
|
||||
| White lamp | PWM0 on PAD_PWM0 (pad 13) | device tree padmux |
|
||||
| IR lamp | PWM4 on PAD_SPI0_CZ (pad 9); OpenIPC drives it as GPIO 9 | padmux; the wiring sheet calls it "PWM1" |
|
||||
| Ethernet LED | PAD_PWM1 (pad 14) | padmux mode LED1 |
|
||||
| Lens/PTZ UART | FUART RX/TX (pads 42/43) = `/dev/ttyS2` | padmux, plus `comm_server` opening `/dev/ttyS2` |
|
||||
| Core voltage select | GPIO 30 (PAD_PM_GPIO4) | `media_server` holds it low; OpenIPC's reference DTS switches it by CPU frequency |
|
||||
| Sensor I2C | I2C1 (pads 58/59), address 0x62 | device tree, sensor driver |
|
||||
|
||||
**How the table was found.**
|
||||
- The app doesn't store pin numbers as strings.
|
||||
- `gpio_init_by_array` is called with a per-board array, chosen by device type. This board is type 0x681.
|
||||
- I found the caller and decoded the array, then decoded the type codes from the getter functions in `libtools.so`. For example, the reset getter looks for type 3.
|
||||
|
||||
**IR-cut direction** took two sources:
|
||||
1. The vendor's day-mode function writes `1` to `/dev/irled`, which pulses GPIO 80. Night mode writes `0`, which pulses GPIO 11. Found by disassembling `media_server`.
|
||||
2. In majestic, `irCutPin1` is the "opens" coil and `irCutPin2` the "closes" coil. Found in majestic-webui's `ircut-scan.js`: `irCutPin1: opensWhenHigh, irCutPin2: closesWhenHigh`. The filter opens at night.
|
||||
|
||||
So `irCutPin1=11` and `irCutPin2=80`.
|
||||
|
||||
**Wiring sheet connectors:**
|
||||
|
||||
| Connector | Pins |
|
||||
|---|---|
|
||||
| D5 (lighting) | CDS in, IR PWM, white PWM |
|
||||
| D6 | IR-cut coil |
|
||||
| D7 | TX/RX (ttyS2), SPKEN, red/blue IO |
|
||||
| D1 | pin 7 = reset, pin 8 = network LED |
|
||||
|
||||
The full map is in `../firmware_MCL18D_V3.6.1.3/gpio_map.md`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Kernel: the device tree
|
||||
|
||||
**Method.**
|
||||
1. Compiled OpenIPC's own `infinity6c-ssc027a-s01a.dts`.
|
||||
- This needed a fake `autoconf.h`, generated from the kernel config, because the DTS includes generated headers.
|
||||
2. Decompiled both DTBs with `dtc -s` (sorted).
|
||||
3. Diffed them node by node.
|
||||
4. Decoded the padmux "schematic" entries, which are pad / mode / purpose triples, into the kernel's macro names.
|
||||
|
||||
**Differences found** (everything else matched):
|
||||
|
||||
| Item | Vendor | OpenIPC reference |
|
||||
|---|---|---|
|
||||
| PAD_PWM0 | PWM0 (white lamp) | I2C0 |
|
||||
| PAD_SPI0_CZ | PWM4 mode 2 (IR lamp) | unused / SPI |
|
||||
| PAD_PWM1 | Ethernet LED (LED1 mode 2) | I2C0 |
|
||||
| PAD_FUART_RX/TX | 2-wire FUART | — |
|
||||
| SD card | 20 MHz, drive strength 0 | 48 MHz, drive 1 |
|
||||
|
||||
**The change** is a thin overlay DTS. It `#include`s the reference DTS and overrides only `padmux` and `sdmmc`, so upstream fixes to the reference still flow in:
|
||||
|
||||
`linux-infinity6c/arch/arm/boot/dts/infinity6c-ssc027a-s01a-mcl18d.dts`
|
||||
|
||||
It is carried into the build as a kernel patch. The board kernel config `infinity6c-ssc027a-mcl18d.config` is a copy of `infinity6c-ssc027a.config` with one line changed:
|
||||
|
||||
```
|
||||
CONFIG_SS_DTB_NAME="infinity6c-ssc027a-s01a-mcl18d"
|
||||
```
|
||||
|
||||
**Verified:**
|
||||
- The kernel's own SigmaStar checks passed during the build: "The configuration of GPIO & PADMUX is correct!" and "PUSE check PASS!".
|
||||
- The DTB extracted from the built uImage has the new padmux and SD settings.
|
||||
- The compiled padmux table matches the vendor's entry for entry.
|
||||
|
||||
**Deliberately not ported:**
|
||||
- **The vendor's `/dev/irled` driver.** majestic drives the IR-cut pins and reads the light sensor itself.
|
||||
- **The core-voltage behaviour on GPIO 30.** OpenIPC's reference design switches it by CPU frequency; I left that alone.
|
||||
|
||||
---
|
||||
|
||||
## 6. The GC5603 sensor driver
|
||||
|
||||
### Why it had to be rewritten
|
||||
|
||||
- OpenIPC/sensors has no GC5603 driver for Infinity6C.
|
||||
- The vendor's `.ko` can't simply be copied in. Its `ms_cus_sensor` struct differs from OpenIPC's in two places. The vendor module would read and write the wrong fields.
|
||||
- **SPI:** the vendor struct has no SPI fields. OpenIPC's has `app_spi_cfg spi_cfg` (12 bytes, packed) and `spi_handle_t *spi_bus` (4 bytes) right after `i2c_bus`. Every field from `sensor_if_api` on sits 16 bytes later in OpenIPC.
|
||||
- **Frame sync:** after `sat_mingain`, the vendor has one 4-byte field and OpenIPC has three: `nPixelSize`, `CurTotalVertLine` and `bChangeVTS` (a `u8` padded to 4). So every callback pointer (`pCus_sensor_poweron` onward) sits 24 bytes later.
|
||||
- **How this was measured:** OpenIPC's offsets were computed with `offsetof` and the ARM toolchain. The vendor's were read from its code: `ldr r6, [r0, #0x40]` in `pCus_poweron` loads `sensor_if_api`, and `cus_camsensor_init_handle` stores each callback at a fixed offset.
|
||||
|
||||
### How it was rebuilt
|
||||
|
||||
1. Disassembled `gc5603_MIPI_1125.ko` with relocations, so calls and table references resolve to names.
|
||||
2. Dumped its read-only data as register/value tables. The C tables were **generated from the binary**, not hand-copied:
|
||||
- init (2960x1666@30)
|
||||
- gain
|
||||
- exposure
|
||||
- VTS (frame length)
|
||||
- mirror/flip
|
||||
3. Recovered the constants from the code:
|
||||
|
||||
| Constant | Value |
|
||||
|---|---|
|
||||
| Bayer order | BG |
|
||||
| Bit depth | 10-bit |
|
||||
| MIPI lanes | 2 |
|
||||
| MCLK | 27 MHz |
|
||||
| I2C | address 0x62, 16-bit register / 8-bit data |
|
||||
| Line period | 19047 ns |
|
||||
| VTS at 30 fps | 1750 |
|
||||
| Gain table | 26 entries, max 128x |
|
||||
|
||||
4. Kept the vendor's temperature-dependent black-level logic:
|
||||
- it reads level registers 0x0410/0x0414 on gain changes;
|
||||
- it writes 0x0451/0x0452/0x0455/0x0456.
|
||||
5. Wrote it in OpenIPC's sensor-driver template style: `sensors/sigmastar/infinity6c/sensor_gc5603_mipi.c`, about 950 lines.
|
||||
|
||||
**One deliberate difference: orientation.**
|
||||
- The vendor maps "no mirror/flip" to register `0x022c=3`, then its app inverts mirror and flip for this board. Net effect: native readout.
|
||||
- Here, "no mirror/flip" *is* native readout, so majestic's `image.mirror`/`image.flip` mean what they say.
|
||||
|
||||
### How it was verified without the camera: a differential test
|
||||
|
||||
`openipc/gc5603-difftest/` runs both modules in an ARM emulator (unicorn):
|
||||
- the vendor `.ko`;
|
||||
- my driver, built with the OpenIPC toolchain.
|
||||
|
||||
`emu_ko.py`:
|
||||
- loads a kernel module;
|
||||
- applies its relocations;
|
||||
- stubs the kernel symbols it calls;
|
||||
- connects it to a **fake sensor** that records every I2C transaction.
|
||||
|
||||
`difftest.py` drives both modules through the same operations and compares every register write:
|
||||
- init and sensor ID;
|
||||
- gain and exposure sweeps;
|
||||
- FPS;
|
||||
- orientation;
|
||||
- temperature levels.
|
||||
|
||||
**Results:**
|
||||
- 76,011 checks, 0 mismatches. The `.ko` actually shipped in the image also passes.
|
||||
- **The test was tested.** Four deliberately planted bugs were each caught, with 82 to 928 mismatches each.
|
||||
- The first two planted bugs were *not* caught, which exposed that the test wasn't reaching the temperature code. I fixed the test before trusting it; see section 17.
|
||||
|
||||
### The IQ (tuning) file
|
||||
|
||||
- The flash dump has no GC5603 IQ file.
|
||||
- `media_server` hard-codes `/config/iqfile/gc4023_day.bin` and `gc4023_night.bin` for this board. That is what your camera really runs with the GC5603.
|
||||
- So the image ships the vendor's `gc4023_day.bin` as `/etc/sensors/gc5603.bin`.
|
||||
- That is a vendor binary blob. It works for your build but can't go upstream (section 15).
|
||||
|
||||
### Wiring it into the build
|
||||
|
||||
- **`general/package/sigmastar-osdrv-sensors/0001-sigmastar-infinity6c-add-gc5603-driver.patch`** adds the driver source to the sensors package. It was generated from the `openipc/sensors` branch `gc5603-infinity6c`.
|
||||
- **`general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar`** gets a new `gc5603)` case arm: `insmod sensor_gc5603_mipi.ko chmap=1`. It is additive; the family default is untouched, as OpenIPC's rules require.
|
||||
- **`general/package/sigmastar-osdrv-infinity6c/files/sensor/configs/gc5603.bin`** is the IQ file.
|
||||
|
||||
---
|
||||
|
||||
## 7. Registering the board in the OpenIPC tree
|
||||
|
||||
`br-ext-chip-sigmastar/configs/ssc377d_mcl18d_defconfig` is a copy of `ssc377d_lite_defconfig` with these differences:
|
||||
|
||||
```diff
|
||||
-BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE=".../infinity6c-ssc027a.config"
|
||||
+BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE=".../infinity6c-ssc027a-mcl18d.config"
|
||||
+BR2_LINUX_KERNEL_PATCH=".../board/infinity6c/mcl18d/linux"
|
||||
-BR2_OPENIPC_FLASH_SIZE="8"
|
||||
+BR2_OPENIPC_FLASH_SIZE="16" # 16 MB NOR: 2 MB kernel + 8 MB rootfs slots
|
||||
+BR2_OPENIPC_SNS_MODEL="gc5603" # default `sensor` env → which driver loads
|
||||
+BR2_PACKAGE_ANJVISION_MCL18D=y # the board package (section 8)
|
||||
+BR2_PACKAGE_ONVIF_SIMPLE_SERVER=y # ONVIF with PTZ (section 9)
|
||||
```
|
||||
|
||||
**Other registration edits:**
|
||||
- **`general/package/Config.in`:** one `source` line for the new package.
|
||||
- **`.github/scripts/ci-matrix.py`:**
|
||||
- `ssc377d_mcl18d` goes in `UNBUILT_BOARDS`, with the reason "single retail device".
|
||||
- `anjvision-mcl18d` goes in `NOT_BUILT`.
|
||||
- `--self-test` passes (107 boards, 158 packages).
|
||||
|
||||
OpenIPC's own rules send single retail devices to OpenIPC/builder, so this is kept as a local port.
|
||||
|
||||
---
|
||||
|
||||
## 8. The board package `anjvision-mcl18d`
|
||||
|
||||
Location: `firmware/general/package/anjvision-mcl18d/`.
|
||||
- `SITE_METHOD = local`: it builds from its own `src/`.
|
||||
- The `.mk` installs each file to its path below.
|
||||
|
||||
| File | Installed as | What it does |
|
||||
|---|---|---|
|
||||
| `Config.in` | — | Kconfig entry; selects `onvif-simple-server` |
|
||||
| `anjvision-mcl18d.mk` | — | Builds `pelco-ptz`, installs everything |
|
||||
| `files/customizer.sh` | `/usr/share/openipc/customizer.sh` | First boot. See below. |
|
||||
| `files/muxes.sh` | `/usr/share/openipc/muxes.sh` | Drives GPIO 10 and 61 to 1 every boot, as the vendor does |
|
||||
| `files/S94mcl18d` | `/etc/init.d/S94mcl18d` | Starts `mcl18d-io`, `pelco-ptz keepalive` (without it the lens board and head ignore every command, section 20), and `wsd_simple_server` (ONVIF discovery, once the interface has an IP) |
|
||||
| `files/mcl18d-io` | `/usr/sbin/mcl18d-io` | Polls every 100 ms. Reset button GPIO 60 held 5 s → `firstboot`. Alarm GPIO 44 changes → syslog + `/etc/mcl18d/alarm-in active\|idle` |
|
||||
| `files/onvif.conf` | `/etc/onvif.conf.mcl18d` | ONVIF config: port 85, two profiles, PTZ hooks calling `pelco-ptz` |
|
||||
| `files/onvif-passwd` | `/usr/sbin/onvif-passwd` | Sets the ONVIF password |
|
||||
| `files/pelco-ptz.conf` | `/etc/pelco-ptz.conf` | Port, baud (57600), address, mounting, presets |
|
||||
| `files/mcl18d-af` | `/usr/sbin/mcl18d-af` | One-shot autofocus (section 11) |
|
||||
| `src/` | `/usr/sbin/pelco-ptz` | C tool for Pelco-D (sections 9 and 11), plus tests |
|
||||
|
||||
**`customizer.sh`, step by step:**
|
||||
|
||||
1. **Writes majestic's pin map:**
|
||||
- `nightMode.irCutPin1 11`, `irCutPin2 80`
|
||||
- `lightSensorPin 23`, `lightMonitor true`
|
||||
- `backlightPin 9`
|
||||
- `irLightPwmChannel 4`, `whiteLightPwmChannel 0`
|
||||
- `irCut`, `backlight` and `whiteLight` set to `auto`
|
||||
- `audio.speakerPin 12`
|
||||
|
||||
The key names came from majestic's strings and the web UI. They exist in the infinity6c majestic build.
|
||||
|
||||
`lightMonitor` and `backlightPin` came from the camera (section 20). Without `lightMonitor true` majestic never reads the light sensor, so night mode never runs. This majestic brings up no PWM lamp on infinity6c, so `backlightPin 9` drives the IR lamp's pad as a plain GPIO, high at night.
|
||||
2. **Turns off majestic's own ONVIF** (`.onvif.enabled false`), so NVRs find only the PTZ-capable server.
|
||||
3. **Sets the streams:**
|
||||
- `video0.size 2560x1440` (main);
|
||||
- `video1.enabled true`, `video1.size 640x360` (sub).
|
||||
|
||||
These match the ONVIF profiles and the vendor: your camera's saved `config.xml` streams `2560X1440`, and the spec sheet lists 2560×1440 as the 30 fps main stream. The sensor outputs 2960×1666, so full size is possible in principle but untested.
|
||||
4. **Copies `/etc/onvif.conf.mcl18d` to `/etc/onvif.conf`** with a random password, so the camera never answers ONVIF with a password anyone else knows.
|
||||
|
||||
**Why `customizer.sh` and `muxes.sh`:** they are OpenIPC's sanctioned per-device seams. Shared files like `general/overlay/` must not carry board-specific GPIO numbers.
|
||||
|
||||
**Why the reset button and alarm are a shell loop:** majestic doesn't handle them on this chip. The script uses only busybox applets that are in the image, which I checked.
|
||||
|
||||
---
|
||||
|
||||
## 9. PTZ over ONVIF
|
||||
|
||||
### Why majestic can't do it here
|
||||
|
||||
- OpenIPC's PTZ plugin is `majestic-af`, which already speaks Pelco-D. majestic loads it only when its "Motorized lens" settings enable it. Those settings are seeded from U-Boot variables `ptz_control`, `ptz_port`, `ptz_speed`.
|
||||
- I compared majestic's strings for two chip families:
|
||||
- the **infinity6e** build has that settings section;
|
||||
- the **infinity6c** build (this chip) does not.
|
||||
- majestic is closed source, so it can't be added.
|
||||
- I tried enabling `majestic-af`, confirmed it could never load, and reverted it.
|
||||
|
||||
### The route taken: `onvif-simple-server` + `pelco-ptz`
|
||||
|
||||
`onvif-simple-server` is an open-source ONVIF server already packaged in OpenIPC. It runs as a CGI on port 85, and its PTZ requests run shell commands from `onvif.conf`. All of them point at `pelco-ptz`.
|
||||
|
||||
**`pelco-ptz`** (C, in `src/`) runs one command per invocation:
|
||||
|
||||
```
|
||||
pelco-ptz move left|right|up|down|in|out [SPEED] continuous, speed 0..1
|
||||
pelco-ptz focus near|far | iris open|close until stop
|
||||
pelco-ptz stop
|
||||
pelco-ptz abs X Y Z / rel DX DY DZ ("nan" leaves an axis alone)
|
||||
pelco-ptz position / moving
|
||||
pelco-ptz home | sethome | preset list|set NAME|goto N|remove N
|
||||
```
|
||||
|
||||
**Design choices:**
|
||||
|
||||
- **Code split:** `pelco.c` holds pure functions (frames and coordinate maths) with no I/O, so tests can pin every byte. `main.c` does the serial port, locking, state and presets.
|
||||
- **Coordinates:**
|
||||
- pan −1..1 = −180..180°;
|
||||
- tilt −1..1 = −90..90°, up positive (Pelco counts tilt down-positive, so it's converted);
|
||||
- zoom 0..1 = 0..65535.
|
||||
- **Absolute and relative moves:**
|
||||
- Absolute uses Pelco-D's extended "set position" commands 0x4B / 0x4D / 0x4F.
|
||||
- Relative asks the head where it is (queries 0x51 / 0x53 / 0x55, replies 0x59 / 0x5B / 0x5D), adds the offset, then moves absolutely.
|
||||
- A head that doesn't answer gets the last position `pelco-ptz` commanded.
|
||||
- **Diagonals:**
|
||||
- Pelco-D sets the whole motion in one frame, but ONVIF clients send pan and tilt as separate calls.
|
||||
- Axes set within 300 ms of each other are combined into one frame. Older ones are dropped, as ONVIF's "new velocity replaces the old" requires.
|
||||
- **Presets:**
|
||||
- 2..32 are stored in `/etc/pelco-ptz.presets` as `N=name,x,y,z`.
|
||||
- Preset 1 is home.
|
||||
- **Locking:** an exclusive `flock` stops two requests interleaving frames. Motion state is kept in `/tmp/pelco-ptz.state`.
|
||||
|
||||
### Bugs fixed in onvif-simple-server
|
||||
|
||||
`general/package/onvif-simple-server/03-ptz-absolute-relative-zoom-fixes.patch` fixes these upstream bugs, found while testing:
|
||||
|
||||
- A pan/tilt AbsoluteMove passed 0 for the missing zoom, so it drove the lens **fully wide** every time. It now passes NAN, meaning "leave it".
|
||||
- Zoom-only Absolute/RelativeMove ran an **uninitialised command buffer** through `system()`.
|
||||
- An empty RelativeMove was accepted.
|
||||
- `strcmp` was called on a Zoom space that could be NULL, which is a crash.
|
||||
- SetPreset `sscanf`'d `%s` into an int, which is memory corruption.
|
||||
- The FOV-space relative move was rescaled to the configured ranges.
|
||||
|
||||
The upstream package is pinned at `roleoroleo/onvif_simple_server` 7c8672f. My working copy is `openipc/onvif_simple_server`, branch `ptz-fixes`.
|
||||
|
||||
**Wiring note:** D7 is a 3.3 V UART. A typical RS-485 Pelco head needs a TTL-to-RS-485 adapter.
|
||||
|
||||
---
|
||||
|
||||
## 10. The lens board (zoom / focus) protocol
|
||||
|
||||
Full spec: `AF-BOARD-PROTOCOL.md`. Reproduction scripts: `af-board-re/`.
|
||||
|
||||
### How it was decoded
|
||||
|
||||
- **Static disassembly** of `comm_server` and `media_server`. Along the way:
|
||||
- r2 mislabels this binary's library calls by one PLT entry, so `af-board-re/plt.py` rebuilds the map.
|
||||
- `comm_server` loads addresses with `movw`/`movt` pairs.
|
||||
- `media_server` uses literal pools.
|
||||
- `od.py` resolves both.
|
||||
- **Emulation:** the vendor's own functions were run in unicorn (`af-board-re/emu.py`).
|
||||
- libc is stubbed.
|
||||
- `write()` to the UART is recorded.
|
||||
- The PTZ dispatcher `HandleYuntai` was driven with each command name, and the exact bytes it sends were captured.
|
||||
- The same was done for the six AF data senders and the upgrade routine.
|
||||
- **`af-board-re/verify.py`** re-derives every frame in the doc from the binaries: 40 checks, all pass.
|
||||
|
||||
### What it is
|
||||
|
||||
| Topic | Finding |
|
||||
|---|---|
|
||||
| Link | `/dev/ttyS2` at **57600 8N1** whenever `/opt/ch/af.flag` exists, as it does on your camera. This overrides the configured 2400. |
|
||||
| Why 57600 | The vendor code sets it when `af.flag` is present. The likely reason is bandwidth: an 18-byte AF frame 30 times a second is about 5400 bit/s, which 2400 baud cannot carry. That reason is my inference. |
|
||||
| Commands | Plain Pelco-D, address 1. Focus near `FF 01 01 00 30 30 62`, far `FF 01 00 80 30 30 E1`, iris open/close `…02 00 30 30 63` / `…04 00 30 30 65`, zoom `FF 01 00 20/40 ss ss`. |
|
||||
| AF data | `media_server` reads the ISP's AF statistics every frame and sends two focus values: whole picture and centre window. Gain, day/night, IR-cut and lamp levels go with them. Your config: `CAfV2`, 18 bytes, header `51 01 04 78 01 11`. Factory default: `CAfV3`, 16 bytes. **The board runs autofocus from this stream.** |
|
||||
| Boot | Version query: `END`+sum ×8, then `VER`+sum. The reply holds a lens code and a date. (This board never answered it on OpenIPC, awake or asleep.) |
|
||||
| Keep-alive | **Found on the camera, not in the binaries:** the board, and the pan/tilt behind it, ignore every command unless AF frames keep arriving. The vendor never notices because it streams them from boot. `pelco-ptz keepalive` sends one every 100 ms. See section 20. |
|
||||
| Upgrade | `START`+size; the board pulls 128-byte blocks by address; `OK` ends. Emulated end to end; **risky on a real board.** |
|
||||
|
||||
---
|
||||
|
||||
## 11. Manual focus, iris and `mcl18d-af`
|
||||
|
||||
### Focus and iris in `pelco-ptz`
|
||||
|
||||
- **Frames:** the motion frame gained focus bits (command-1 bit 0 near, command-2 bit 7 far) and iris bits (command-1 bits 1/2).
|
||||
- **Speed bytes:** frames that move only the lens carry a speed in both data bytes, as the vendor sends them:
|
||||
- the zoom speed, or 0x30 for focus/iris (`PELCO_LENS_SPEED`);
|
||||
- a normal Pelco head ignores those bytes when not panning or tilting.
|
||||
- **State:** the motion state is now an array per axis (pan, tilt, zoom, focus, iris), each with its own timestamp for the 300 ms combine rule.
|
||||
- **Config:** `/etc/pelco-ptz.conf` and the compiled default are now **57600**. A pan/tilt head sharing D7 must be set to 57600 too.
|
||||
|
||||
### Why not the board's own autofocus
|
||||
|
||||
It needs the per-frame ISP AF statistics. majestic is closed source and doesn't export them on this chip, so nothing on OpenIPC can produce real AF data frames. `pelco-ptz keepalive` sends frames with constant values purely to keep the board awake; they give its autofocus nothing to climb.
|
||||
|
||||
### What `mcl18d-af` does instead
|
||||
|
||||
A shell script run on the camera. Contrast autofocus from the camera side:
|
||||
|
||||
- **Sharpness measure:** the byte size of a JPEG snapshot.
|
||||
- At a fixed JPEG quality, a sharper picture has more fine detail and compresses less. On the camera a sharp snapshot of the bench was about 338 KB and a blurred one about 126 KB, against 0.1–0.6% between two snapshots of a still scene.
|
||||
- It asks for the **middle third** with `?crop=XxYxWxH` (the syntax came from majestic's strings: "crop must be XxYxWxH"). majestic for this chip refuses it: HTTP 501, "snapshot parameters are not supported on this platform". The script then judges the whole frame.
|
||||
- **The lens it has to work with:**
|
||||
- the motor reports no position, so positions are motor run time;
|
||||
- it is slow: focus lay up to 19 s of motor time away, and the sharp band is about 1.5 s wide;
|
||||
- so a short step from a blurred start changes the picture less than the noise.
|
||||
- **Sweep:** run the motor without stopping and take snapshots as fast as they come, timing each from `/proc/uptime`.
|
||||
- It stops once the picture has risen 5% above where it began and then fallen 3% back from its best twice running: focus has just been passed. It notes when the best snapshot was taken.
|
||||
- It goes `far` first. If the picture gets clearly worse over the first 1.5 s, it turns round; if a whole sweep (`-t`, 45 s) 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.
|
||||
- **Approach:** back off past the best snapshot by how far the motor ran after it plus a margin (`-b`, 1 s), then step back the way the sweep went in `-s` (150 ms) steps, measuring after each, and stop on the first step that is worse.
|
||||
- It never reverses near focus, so gear backlash cannot leave it short. The lens rests one step past the sharpest point.
|
||||
- If the very first change is for the worse, the margin was too small: it backs off again, up to 3 times (`AF_LOST`).
|
||||
- **On the camera:** from either side of focus, 12–27 s, ending at 99.4–99.6% of the best snapshot seen.
|
||||
- **Login:** user/password from `/etc/onvif.conf` (`onvif-passwd` sets them to root's), or `-u`.
|
||||
- **Options:**
|
||||
- `-s` approach step, `-b` back-off, `-t` longest sweep;
|
||||
- `-n` snapshots averaged per approach step, `-w` settle time;
|
||||
- `-g` threshold in thousandths, default 0.5%;
|
||||
- `-c` crop, `-a` URL.
|
||||
- **Logs:** to syslog with tags `AF_START`, `AF_SWEEP`, `AF_BACK`, `AF_STEP`, `AF_DONE`, `AF_CROP_REFUSED`, `AF_SNAPSHOT_FAILED`, `AF_NO_DETAIL`, `AF_LOST`.
|
||||
- **Fallbacks:** a refused crop falls back to the full frame; a scene with no detail ends with `AF_NO_DETAIL`. It always stops the motor on exit.
|
||||
|
||||
---
|
||||
|
||||
## 12. Building
|
||||
|
||||
```sh
|
||||
F=openipc/firmware; O=~/.cache/openipc-mcl18d
|
||||
docker run --rm --user $(id -u):$(id -g) -e HOME=$O/home -e BR2_DL_DIR=$O/dl -e PWD=$F \
|
||||
-v $F:$F -v $O:$O -w $F openipc-builder:24.04 make BOARD=ssc377d_mcl18d TARGET=$O/output
|
||||
```
|
||||
|
||||
**Gotchas hit:**
|
||||
- **Arch can't build it natively.** Buildroot 2024.02's host `tar` fails on this Arch toolchain, so I made an Ubuntu 24.04 image, `openipc-builder:24.04`. It has build-essential, bc, bison, flex, cpio, rsync, unzip, wget, python3, cmake, u-boot-tools and **bsdextrautils**.
|
||||
- **`PWD` must be passed** into the container. The Makefile reads `$PWD` from the environment, and docker doesn't set it.
|
||||
- **`hexdump` is needed.** It comes from bsdextrautils, and the kernel's padmux check (`dtx_diff`) uses it. Without it the build died with a confusing `dtc` "Unable to parse input tree" error.
|
||||
- **Build outside the synced folder.** `/tmp` is RAM, and Seafile would sync gigabytes, so the build lives in `~/.cache/openipc-mcl18d`.
|
||||
- **Rebuilding one package:** `make … br-anjvision-mcl18d-dirclean`, then `make …` again (incremental, about 40 s).
|
||||
|
||||
**Result:**
|
||||
- uImage 1991 / 2048 KB.
|
||||
- rootfs 5264 / 8192 KB.
|
||||
- Images are copied to `openipc/images/`:
|
||||
- `openipc.ssc377d-nor-lite.tgz`
|
||||
- `uImage.ssc377d`
|
||||
- `rootfs.squashfs.ssc377d`
|
||||
|
||||
---
|
||||
|
||||
## 13. Testing: what was tested and how
|
||||
|
||||
| Test | What it proves | Result |
|
||||
|---|---|---|
|
||||
| GC5603 differential test (`gc5603-difftest/`) | My driver writes the same registers as the vendor's for every operation | 76,011 checks, 0 mismatches; 4/4 planted bugs caught |
|
||||
| Kernel build checks | Padmux and pin-use table are consistent | PASS |
|
||||
| `make test` (`src/tests/pelco_test.c`) | Every Pelco-D frame byte for byte, including the vendor's focus/iris frames; coordinate maths; reply parsing; combine rule | all pass |
|
||||
| `make e2e` (`src/tests/pelco_e2e.py`) | The real `pelco-ptz` binary against a simulated head on a pseudo-terminal, including focus/iris | all pass |
|
||||
| `tests/onvif_e2e.py` | Real ONVIF SOAP requests → patched server → `pelco-ptz` → simulated head | 23/23 pass; the unpatched server fails 7 |
|
||||
| `make af BUSYBOX=…` (`src/tests/af_sim.py`) | `mcl18d-af`, comment-stripped as it ships, under a host build of the tree's own busybox `ash`, against a simulated lens with backlash, noise, end stops and, in one case, late snapshots | 14 checks, all pass |
|
||||
| `af-board-re/verify.py` | Every lens-protocol frame in the doc, re-derived from the vendor binaries | 40/40 |
|
||||
| `ci-matrix.py --self-test`, `test_shell_parse.sh`, `test_strip_shell_comments.sh` | Tree rules; every shipped script parses before and after stripping | pass |
|
||||
|
||||
The `mcl18d-af` simulation covers:
|
||||
- starting on either side of focus;
|
||||
- starting at focus;
|
||||
- starting far out;
|
||||
- snapshots that show the lens 150 ms late;
|
||||
- a refused crop;
|
||||
- a wrong login;
|
||||
- a featureless scene.
|
||||
|
||||
**Why a host busybox:** the camera's `ash` isn't bash. I built busybox from the tree's own source and `.config` with the host compiler, so the script is tested under the same shell it ships with.
|
||||
|
||||
---
|
||||
|
||||
## 14. Not verified on hardware: first-boot checklist
|
||||
|
||||
Written before the camera was available. Most of it has since been checked; section 20 has the results.
|
||||
|
||||
**Before flashing:**
|
||||
- Flashing needs OpenIPC's U-Boot for SSC377D and a **serial console**.
|
||||
- Keep `backup-ssc377d-nor16m.bin`.
|
||||
|
||||
**Video and board I/O:**
|
||||
1. `dmesg` shows `sensor_gc5603_mipi` loading, and `fw_printenv sensor` says `gc5603`.
|
||||
2. The picture is upright. If not, set `image.mirror` / `image.flip`.
|
||||
3. Day/night switches the right way. If not, set `nightMode.lightSensorInvert`.
|
||||
4. The IR-cut clicks the right way.
|
||||
5. GPIO 10 = 1 leaves the red/blue light off, and GPIO 61 = 1 is right for the light board.
|
||||
6. SD card, microphone, speaker (`audio.speakerPinInvert` if silent), reset button, alarm input.
|
||||
|
||||
**PTZ:**
|
||||
- From the shell: `pelco-ptz move left 0.5`, then `pelco-ptz stop`.
|
||||
- Then an ONVIF client on port 85, after running `onvif-passwd` with root's password.
|
||||
|
||||
**Lens board:**
|
||||
- `pelco-ptz focus far`, then `pelco-ptz stop`.
|
||||
- Check that the board **holds focus** with no AF data frames arriving. The protocol doesn't say what it does then.
|
||||
- Check that `/image.jpg?crop=` works.
|
||||
- Check how much a still scene's JPEG size varies between shots. If it varies more than 0.5%, raise `mcl18d-af -g`.
|
||||
- Tune `-s` and `-m` to the motor's real speed.
|
||||
|
||||
---
|
||||
|
||||
## 15. Upstreaming: what OpenIPC would and would not accept
|
||||
|
||||
From `openipc/firmware/CLAUDE.md` and its `best_practices.md`:
|
||||
|
||||
**Where each part belongs:**
|
||||
- driver → OpenIPC/sensors;
|
||||
- device tree → OpenIPC/linux;
|
||||
- single-device board files → OpenIPC/builder (`devices/<board>/`).
|
||||
|
||||
**Not acceptable as is:**
|
||||
- Register tables copied from a vendor driver ("a register table copied out of a camera vendor's driver is the same problem written in C").
|
||||
- `gc5603.bin`, a binary lifted from a factory image.
|
||||
|
||||
**Fine:**
|
||||
- The additive `load_sigmastar` case arm.
|
||||
- The onvif-simple-server fixes, as a pull request to `roleoroleo/onvif_simple_server`.
|
||||
|
||||
**Never** accept majestic's EULA on someone's behalf. It's accepted by the owner at first claim.
|
||||
|
||||
---
|
||||
|
||||
## 16. Every file changed, by repository
|
||||
|
||||
Nothing is committed. All changes are on local branches.
|
||||
|
||||
### `openipc/firmware` (tag `latest` = 7d213e9, branch `mcl18d-port`)
|
||||
|
||||
| Status | Path |
|
||||
|---|---|
|
||||
| new | `br-ext-chip-sigmastar/configs/ssc377d_mcl18d_defconfig` |
|
||||
| new | `br-ext-chip-sigmastar/board/infinity6c/infinity6c-ssc027a-mcl18d.config` |
|
||||
| new | `br-ext-chip-sigmastar/board/infinity6c/mcl18d/linux/0001-arm-dts-infinity6c-add-anjvision-mc-l18d.patch` |
|
||||
| new | `general/package/sigmastar-osdrv-sensors/0001-sigmastar-infinity6c-add-gc5603-driver.patch` |
|
||||
| new | `general/package/sigmastar-osdrv-infinity6c/files/sensor/configs/gc5603.bin` |
|
||||
| modified | `general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar` (`gc5603)` arm) |
|
||||
| new | `general/package/onvif-simple-server/03-ptz-absolute-relative-zoom-fixes.patch` |
|
||||
| new | `general/package/anjvision-mcl18d/`: Config.in, .mk, files/*, src/* (section 8) |
|
||||
| modified | `general/package/Config.in` (source line) |
|
||||
| modified | `.github/scripts/ci-matrix.py` (UNBUILT_BOARDS, NOT_BUILT) |
|
||||
|
||||
### `openipc/sensors` (branch `gc5603-infinity6c`)
|
||||
|
||||
| Status | Path |
|
||||
|---|---|
|
||||
| new | `sigmastar/infinity6c/sensor_gc5603_mipi.c` |
|
||||
|
||||
### `openipc/linux-infinity6c` (branch `mcl18d`)
|
||||
|
||||
| Status | Path |
|
||||
|---|---|
|
||||
| new | `arch/arm/boot/dts/infinity6c-ssc027a-s01a-mcl18d.dts` |
|
||||
|
||||
### `openipc/onvif_simple_server` (branch `ptz-fixes`)
|
||||
|
||||
The source of the onvif patch.
|
||||
|
||||
### Other folders in `openipc/`
|
||||
|
||||
| Folder | Contents |
|
||||
|---|---|
|
||||
| `ipctool/` | Reference only; it already detects GC5603 |
|
||||
| `majestic-af/` | Reference; pinned 67a9631 |
|
||||
| `gc5603-difftest/` | The differential sensor test |
|
||||
| `af-board-re/` | Lens-protocol emulator and checks |
|
||||
| `images/` | The built firmware |
|
||||
| `MCL18D-PORT.md`, `AF-BOARD-PROTOCOL.md`, this file | Notes |
|
||||
|
||||
### Outside `openipc/`
|
||||
|
||||
| Item | Contents |
|
||||
|---|---|
|
||||
| `firmware_MCL18D_V3.6.1.3/` | The unpacked update file, plus `gpio_map.md` and `board.dts` |
|
||||
| `flash_dump_ssc377d/` | The unpacked flash dump |
|
||||
| `~/.cache/openipc-mcl18d/` | Build tree, download cache, logs |
|
||||
|
||||
---
|
||||
|
||||
## 17. Mistakes made and corrected
|
||||
|
||||
These are worth reading. Each one is a trap you'll meet in this kind of work.
|
||||
|
||||
1. **"The lens board talks `FC 01` at 115200."** I first said this from a partial read.
|
||||
- The `FC` frames and the 115200 channel exist in `comm_server`, but only for other customers' builds (`af_protocol_5_flag`, `_MY` on `/dev/ttyS4`).
|
||||
- Tracing the `af.flag` path showed 57600 and plain Pelco-D for this camera.
|
||||
- Lesson: a byte pattern in a binary tells you it exists, not that *your* configuration uses it. Follow the flags.
|
||||
2. **A test that couldn't fail.** The first sensor difftest reported 0 mismatches, but two planted bugs in the temperature code weren't caught either.
|
||||
- The test never reached that code.
|
||||
- I extended it until all planted bugs were caught.
|
||||
- Lesson: always prove a test can fail.
|
||||
3. **Emulator stubs out of branch range.** ARM `BL` reaches ±16 MB. My stub area was 256 MB away, so calls landed in the wrong function. I moved the stubs inside the code mapping.
|
||||
4. **r2 PLT names off by one.** radare2 and objdump labelled this binary's imported calls with the neighbouring entry's name. `plt.py` reads each PLT stub's own instructions and follows it to its `JUMP_SLOT` relocation instead.
|
||||
5. **Stray files.** An earlier r2 command with redirects left junk files in `flash_dump_ssc377d/rootfs/opt/ch/`. I deleted them.
|
||||
6. **Docker build "finished" instantly.** The Makefile needs `$PWD`, and the wrapper's exit code hid make's failure. Lesson: read the log, not the exit code.
|
||||
7. **Missing `hexdump`** in the container produced a misleading `dtc` error deep in the kernel build.
|
||||
8. **`mcl18d-af -h` printed nothing on the camera.** It read its help from its own header comments, and the build strips comments. I rewrote it as real text, and the test now runs the stripped copy.
|
||||
9. **Autofocus overshoot logic.** After overshooting, my first version turned back toward the side it already knew was worse, and landed short. The simulator showed it. The fix: after an overshoot, keep the direction and halve the step.
|
||||
10. **Zoom frames.** My first `pelco-ptz` sent zoom with zero data bytes. The vendor puts a speed there for the lens board, so I now match the vendor.
|
||||
11. **A patch exported with `git diff` picked up a generated file.** The kernel build rewrites `ms_version.h`. The first DTS patch carried that rewrite alongside the DTS, and I found it when cross-checking each patch against its source branch. It was harmless only because the kernel regenerates the file on every build. Lesson: export a patch by naming the paths, and read the `diff --git` lines before shipping it.
|
||||
12. **"The camera never reads the port."** I wrote that in `AF-BOARD-PROTOCOL.md` from `comm_server` alone. `media_server` opens the same port and reads the board's frames. Lesson: a port can have more than one owner; search every binary for the device name.
|
||||
13. **Plain Pelco-D is enough.** I matched the vendor's command frames byte for byte and assumed that was the whole interface. The board also needed the AF stream to be awake, which no amount of reading `comm_server` would show, because the vendor never lets it sleep. Lesson: reproduce everything the vendor puts on the wire, not just the part you think matters.
|
||||
14. **A rising TX counter is not a transmission.** `/proc/tty/driver` counts bytes when the DMA driver copies them into its ring buffer, not when they leave the pin. Timing a write at 2400 baud proved they did leave.
|
||||
15. **Reading the FUART's registers crashed the camera.** A `devmem` read of the UART block hit a register-bus timeout, and the SigmaStar kernel treats that as fatal (`MDrv_RIU_TIMEOUT_interrupt`, then `SW Reset`). The pad-mux and clock banks read safely. Lesson: on SigmaStar, probe one bank before scripting a whole dump.
|
||||
16. **Two dead ends on the colour flares, and one wrong conclusion.** First I suspected UART traffic, then the sensor's black-level writes. The flares carried on with the port silent, and in that gain band the black level never changes. Then I wrote that heat was the cause, because refitting the heat sink cut them from every 5–15 s to about one a minute. They did not stop, and the cause is still open (section 20). Lessons: rule out the hardware's state (temperature, supply) before reading driver code, and "rarer" is not "gone".
|
||||
17. **`pkill -f` killed my own shell twice**, because the pattern also matched the command line that ran it. Write the pattern so it can't match itself (`[s]erd\.py`).
|
||||
18. **Hill-climbing a slow motor.** The first `mcl18d-af` stepped the motor a few hundred ms at a time, judged each step, and reversed when it got worse. From a blurred start a step changed the picture less than the noise, and every reversal near focus lost travel to backlash, so it ended short of focus. The simulator had a lens that travelled 1.5 s end to end; the real one needed up to 19 s. Lesson: measure the actuator before tuning a search for it.
|
||||
19. **A snapshot is late.** The sweep's second leg once gave up the moment it started, because the picture was still getting worse from the first leg. The fix was to let only the first sweep turn round, and the simulator now has a case with late snapshots.
|
||||
20. **"GPIO 61 enables the light board."** I named it from where it sits in the vendor's IO table, among the lamps. Following its type code (12) to the code that uses it, `mainctrl`'s `GetLedBrGpioPort`, showed an active-low warning light that goes low on alarm. Lesson: name a pin by what its consumer does with it.
|
||||
21. **Night mode configured but never running.** The pin map had the light sensor, but majestic's `lightMonitor` was off, so it never read the pin. Lesson: check the running state (`night_mode_source` in `/metrics`), not just the config.
|
||||
|
||||
---
|
||||
|
||||
## 18. Loose ends in the folder
|
||||
|
||||
- **Two files I didn't make:** `firmware_MCL18D_V3.6.1.3/passwd_sys.orig.bak` and `rootfs.new.squashfs`, created Oct 27 at 23:15.
|
||||
- They don't appear in anything I ran in these sessions.
|
||||
- The name suggests someone edited `passwd_sys` and repacked the rootfs.
|
||||
- Check them before using that folder as a clean reference.
|
||||
- **`ms_version.h`** in `linux-infinity6c`: the kernel's build regenerates it, and that edit was swept into the first export of the device-tree patch. The kernel regenerates the file on every build, so it never changed the image. It is now reverted, and the patch holds only the DTS (section 17).
|
||||
- **The scratchpad** under `/tmp/claude-1000/…` holds intermediate files: listings, the host busybox, the native onvif build. It isn't needed for anything shipped and disappears on reboot.
|
||||
|
||||
---
|
||||
|
||||
## 19. Techniques worth reusing
|
||||
|
||||
- **Diff device trees after normalising them.** Compile both, decompile with `dtc -s`, and compare. Raw sources differ in includes and macros.
|
||||
- **Find tables by their callers, not by searching for numbers.** Find the function that consumes the table (here `gpio_init_by_array`), then follow its argument.
|
||||
- **Emulate instead of reading branchy code.** Load the binary in unicorn, stub libc, capture output syscalls, and drive the real function with real inputs. It is often faster and more trustworthy than static reading.
|
||||
- **Differential testing for rewrites.** Run old and new against the same fake hardware, compare every transaction, and then prove the comparison catches planted bugs.
|
||||
- **Generate tables from binaries, never hand-copy them.**
|
||||
- **Test shell scripts under the shell they ship with,** after the build's own transformations (comment stripping).
|
||||
- **Keep board specifics in the sanctioned seams:** `customizer.sh`, `muxes.sh`, the board package. Shared files reach every camera.
|
||||
|
||||
---
|
||||
|
||||
## 20. On the hardware: bring-up, 2026-10-28/29
|
||||
|
||||
What happened once the camera was on the bench, in the order it was learned.
|
||||
|
||||
### The bench
|
||||
|
||||
- **Power:** a Tasmota plug (`http://192.168.1.41/cm?cmnd=Power%20On|Off`, `Status%2010` reads watts). Power-cycling plus the console is enough to drive U-Boot unattended.
|
||||
- **Console:** an FT232R on the camera's UART0 at 115200. These boards often have a 5 V / 3.3 V jumper; it must be on 3.3 V.
|
||||
- **Images:** served over TFTP from the PC's existing `uftpd` (`/srv/ftp/openipc-mcl18d/`).
|
||||
|
||||
### Getting into U-Boot
|
||||
|
||||
- **The vendor's U-Boot** (the stock image) ignores Ctrl-C. Its key is `bootdelaykey`, which is unset, so the default is Enter (`\r`). With `bootdelay=0` it looks for the key only twice, so the Enter has to be in the UART buffer already: send it continuously from power-on.
|
||||
- **OpenIPC's U-Boot** sets `rootmtd` (5120k or 8192k) on every `sf probe`, from the size of the squashfs already in flash. `fw_setenv rootmtd` is therefore overwritten at boot. Writing the larger rootfs from U-Boot is what moves the camera to the 8192k layout.
|
||||
- **Flash safely:** load to RAM, check the image's `crc32` against the PC's, write everything except the boot area first, write the boot area last in one command line, read back and compare.
|
||||
|
||||
### The first claim
|
||||
|
||||
The camera ships unclaimed. Root's password is set at the first login, and that same step accepts the Majestic EULA, which only the owner may do. An AI must not type "I agree" (`firmware/CLAUDE.md`).
|
||||
|
||||
### The heat sink
|
||||
|
||||
- **Symptoms:** resets every few minutes, also idle at the U-Boot prompt; the boot ROM's memory test failing (`BIST0_0001-FAIL`); a kernel oops on memory holding `0xdead4ead` (the spinlock debug marker) in path lookup, hitting `majestic` and `dropbear` at the same moment; frames turning to coloured noise every 5-15 s.
|
||||
- **The boot ROM prints the reset's cause.** Every one was `HW Reset`, not `WDT Reset` (watchdog) or `SW Reset` (a panic or `reboot`). That ruled out software.
|
||||
- **Temperature:** majestic's `/metrics` reports it (`node_hwmon_temp_celsius`): 76 C. With the heat sink refitted, 63 C steady, no more resets or oopses, and flares only at start-up and about one a minute. They did not go away; see below.
|
||||
- **What a flare is:** one frame where the dark areas fill with coloured noise below a random row, faded out over the next frames by the noise filter. A random start row means an event at a random moment, not a register write at frame start.
|
||||
|
||||
### Why nothing on D7 moved
|
||||
|
||||
1. **The camera side was right.** The pad mux (`PADTOP 0x6e = 0x1000`, FUART_2W_MODE_1), the clock and the vendor's settings all matched. Writing 64 bytes at 2400 baud took as long as sending them, so they left the UART.
|
||||
2. **Nothing ever came back:** rx stayed 0, at every baud from 2400 to 115200, Pelco-D at address 0 and 1, and Pelco-P.
|
||||
3. **Copying the rest of the vendor's traffic woke it.** A few CAfV2 AF frames, then a zoom: the picture zoomed, and the board sent its first bytes ever (`51 01 04 78 01 0a …`).
|
||||
4. **Measured:** five frames wake it, one does not; it still obeys 3 s later and has gone back to sleep by 40 s; one frame every 100 ms keeps it awake. Pan and tilt sleep and wake with it.
|
||||
5. **The fix:** `pelco-ptz keepalive`, started by `S94mcl18d`.
|
||||
|
||||
### Absolute positions
|
||||
|
||||
The head ignores Pelco-D set-position (0x4B/0x4D/0x4F), even after "set zero" (0x49), and never answers position queries. Presets work: set one, move away, go to it, and it is back. So presets are its only absolute positions, and `onvif.conf` no longer offers AbsoluteMove or RelativeMove, which would have been acknowledged and done nothing.
|
||||
|
||||
### How a picture became the measuring instrument
|
||||
|
||||
With no feedback from the head, every test compared snapshots: the mean pixel difference for "did it move", phase correlation for pan/tilt shift, a scale search for zoom, and Laplacian variance for focus. Blurry or low-contrast scenes defeat the shift estimate, so the frames themselves were checked by eye whenever the numbers disagreed.
|
||||
|
||||
### Autofocus on the real lens
|
||||
|
||||
The first `mcl18d-af` was tuned on a simulated lens and did not survive the real one (section 17, mistakes 18 and 19). What the camera showed:
|
||||
- the snapshot size is a strong signal: about 338 KB in focus against 126 KB blurred, with 0.1–0.6% noise;
|
||||
- the motor is slow: focus was up to 19 s of motor time away, and the sharp band about 1.5 s wide;
|
||||
- `?crop=` returns 501, so it judges the whole frame.
|
||||
|
||||
So it now sweeps first and finishes with a one-way approach (section 11). From either side of focus it takes 12–27 s and ends at 99.4–99.6% of the best snapshot it saw.
|
||||
|
||||
### Night mode, the IR lamp and the light sensor
|
||||
|
||||
- **What the vendor does**, from `media_server` and the `/dev/irled` driver:
|
||||
- this unit's saved IR-cut mode is 2, "Passive": day and night come from GPIO 23 alone;
|
||||
- in that mode the light board lights its own IR LEDs from its own photoresistor and reports the result on GPIO 23 (`IRDET`), 1 by day and 0 at night;
|
||||
- the SAR ADC light reading in `media_server` is for other customers' builds (`_KO`);
|
||||
- in its other modes the vendor holds PWM4, the IR lamp, at 100% at night;
|
||||
- `/dev/irled` only pulses the IR-cut (GPIO 11 for night, GPIO 80 for day, 250 ms) and reads GPIO 23.
|
||||
- **What OpenIPC needed:**
|
||||
- `lightMonitor true`, without which majestic never reads the sensor. Then `/metrics` shows `night_mode_source 1`;
|
||||
- `backlightPin 9`, because this majestic brings up no PWM lamp on infinity6c. It drives the IR lamp's pad as a GPIO instead, high at night.
|
||||
- **Checked:** forcing night by inverting the sensor for a moment, majestic opened the IR-cut, went grey and drove GPIO 9 high.
|
||||
- **Not seen:** GPIO 23 read 1 with the room lights on and off, and nothing lit the scene with PWM4 at 0% or 100% or GPIO 9 high. Either the board waits for real darkness at its own photoresistor, which a dark room may not give it, or it has no power. Next: cover the photoresistor in a dark room and watch GPIO 23 and the LEDs (a phone camera sees IR), and check the light board's supply on D5.
|
||||
|
||||
### The colour flares that remain
|
||||
|
||||
- **What they look like:** below a random row, the frame is random coloured noise. They come mostly within seconds of a large change in lighting, such as the room lights going on or off.
|
||||
- **Ruled out:**
|
||||
- UART traffic;
|
||||
- the driver's black-level writes, also forced during exposure changes;
|
||||
- the motors;
|
||||
- writes of the frame length, the gain index or the analog gain page in the middle of a frame;
|
||||
- VIF rewinds and FIFO errors.
|
||||
- **Same as the vendor:** the vendor driver writes its exposure registers at the same point as this one (`CUS_FRAME_ACTIVE`, status 1).
|
||||
- **Open.** The next test is the stock firmware on the same board, in the same scene: if it flares too, the cause is the hardware.
|
||||
|
||||
### Loose ends from the bench
|
||||
|
||||
- majestic logs `set_gpio(12, 0) error`, about the speaker-enable pin, at every start. Not looked into.
|
||||
- A majestic restart once left a zombie process with stuck threads; a reboot cleared it.
|
||||
- Time-based pan moves are not a way back to a position: in one trial, 1 s right then 1 s left at half speed left the picture differing from the start by a mean pixel difference of 36, against 50 for the move itself. Use presets for positions.
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
# OpenIPC on the AnjoyVision MC-L18D (SSC377D + GC5603)
|
||||
|
||||
Sources analysed: `backup-ssc377d-nor16m.bin` (full 16 MB NOR dump, extracted to
|
||||
`../flash_dump_ssc377d/`) and the vendor update `r1885__firmware_MCL18D_...bin`
|
||||
(extracted to `../firmware_MCL18D_V3.6.1.3/`). Both carry the same kernel and the
|
||||
same GC5603 driver; the rootfs in the flash dump is an older app build.
|
||||
|
||||
## Layout of this folder
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| `firmware/` | OpenIPC/firmware at tag `latest` (7d213e9), branch `mcl18d-port`, changes uncommitted |
|
||||
| `sensors/` | OpenIPC/sensors, branch `gc5603-infinity6c`, new `sigmastar/infinity6c/sensor_gc5603_mipi.c` |
|
||||
| `linux-infinity6c/` | OpenIPC/linux `sigmastar-infinity6c`, branch `mcl18d`, new MC-L18D device tree |
|
||||
| `ipctool/` | OpenIPC/ipctool, reference only (it already detects GC5603) |
|
||||
| `images/` | built firmware: `openipc.ssc377d-nor-lite.tgz`, `uImage.ssc377d`, `rootfs.squashfs.ssc377d` |
|
||||
| `gc5603-difftest/` | emulator harness comparing the vendor and rebuilt GC5603 modules |
|
||||
| `AF-BOARD-PROTOCOL.md`, `af-board-re/` | the lens (AF/zoom) board protocol, and the emulator checks behind it |
|
||||
| `TECH-SPEC.md` | technical specification: interfaces, configs, protocols, algorithms, verification matrix |
|
||||
| `LEARNING-GUIDE.md` | the whole port explained: sources for every fact, every change, tests, mistakes |
|
||||
|
||||
Build: `make BOARD=ssc377d_mcl18d` in `firmware/` on Ubuntu 24.04. This Arch host
|
||||
cannot build Buildroot 2024.02's host-tar, so the build was run in a container
|
||||
(Ubuntu 24.04 plus build-essential, bc, bison, flex, cpio, rsync, unzip, wget,
|
||||
python3, cmake, u-boot-tools, and bsdextrautils for the kernel's padmux check):
|
||||
|
||||
```sh
|
||||
docker run --rm --user $(id -u):$(id -g) -e HOME=$O/home -e BR2_DL_DIR=$O/dl -e PWD=$F \
|
||||
-v $F:$F -v $O:$O -w $F openipc-builder:24.04 make BOARD=ssc377d_mcl18d TARGET=$O/output
|
||||
```
|
||||
|
||||
with `F` the `firmware/` path and `O=~/.cache/openipc-mcl18d`.
|
||||
|
||||
## Changes in firmware/
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `br-ext-chip-sigmastar/configs/ssc377d_mcl18d_defconfig` | ssc377d_lite plus: board kernel config and patch dir, 16 MB flash, `SNS_MODEL=gc5603`, board package |
|
||||
| `br-ext-chip-sigmastar/board/infinity6c/infinity6c-ssc027a-mcl18d.config` | ssc027a kernel config with `CONFIG_SS_DTB_NAME="infinity6c-ssc027a-s01a-mcl18d"` |
|
||||
| `br-ext-chip-sigmastar/board/infinity6c/mcl18d/linux/0001-...patch` | adds the MC-L18D device tree (from `linux-infinity6c/`) |
|
||||
| `general/package/sigmastar-osdrv-sensors/0001-...gc5603-driver.patch` | adds the GC5603 driver (from `sensors/`) |
|
||||
| `general/package/sigmastar-osdrv-infinity6c/files/script/load_sigmastar` | `gc5603)` case arm |
|
||||
| `general/package/sigmastar-osdrv-infinity6c/files/sensor/configs/gc5603.bin` | IQ file: the flash dump's `/config/iqfile/gc4023_day.bin` |
|
||||
| `general/package/anjvision-mcl18d/` | `customizer.sh` (majestic pin map, ONVIF setup), `muxes.sh` (boot GPIO levels), `mcl18d-io` (reset button, alarm in), `pelco-ptz` (C, built from `src/`), `mcl18d-af` (autofocus), `onvif.conf`, `pelco-ptz.conf`, `onvif-passwd` |
|
||||
| `general/package/onvif-simple-server/03-ptz-absolute-relative-zoom-fixes.patch` | upstream fixes for absolute/relative moves (see PTZ below) |
|
||||
| `general/package/Config.in`, `.github/scripts/ci-matrix.py` | registration |
|
||||
|
||||
## Kernel changes carried over
|
||||
|
||||
The vendor kernel is SigmaStar's SSC027A-S01A reference build. Against OpenIPC's
|
||||
SSC027A device tree, the board-level differences are:
|
||||
|
||||
- Pad mux: `PAD_PWM0` is PWM0 (white lamp), `PAD_SPI0_CZ` is PWM4 (IR lamp),
|
||||
`PAD_PWM1` is the Ethernet LED, `PAD_FUART_RX/TX` are the 2-wire FUART for the
|
||||
zoom/PTZ board. OpenIPC's default puts I2C0 on the PWM pads.
|
||||
- SD card at 20 MHz with drive strength 0 (OpenIPC default 48 MHz, drive 1).
|
||||
|
||||
The compiled padmux table matches the vendor's entry for entry. Pad numbering is
|
||||
identical between the two kernels.
|
||||
|
||||
Not carried over, on purpose:
|
||||
|
||||
- The vendor's built-in `/dev/irled` driver. It pulses the IR-cut pins and reads
|
||||
the CDS pin; majestic does both from `customizer.sh`'s pin map.
|
||||
- Core voltage: OpenIPC's reference tree switches 900/1000 mV on `PAD_PM_GPIO4`
|
||||
(GPIO 30) by CPU frequency. The vendor has no regulator node and its
|
||||
`media_server` holds GPIO 30 low. OpenIPC's behaviour is the reference design's.
|
||||
|
||||
## GC5603 driver
|
||||
|
||||
Rebuilt in C from the vendor's `gc5603_MIPI_1125.ko`: 2960x1666@30, 2-lane MIPI,
|
||||
27 MHz MCLK, I2C 0x62, BG Bayer, 10-bit. The vendor module cannot be loaded
|
||||
as-is: its `ms_cus_sensor` has no SPI fields, which OpenIPC's has (`spi_cfg`,
|
||||
12 bytes, and `spi_bus`, 4), so everything past the I2C bus pointer sits 16 bytes
|
||||
off. After `sat_mingain`, OpenIPC also has `CurTotalVertLine` and `bChangeVTS`
|
||||
(8 bytes with padding) where the vendor has nothing, so every callback pointer
|
||||
sits 24 bytes off.
|
||||
|
||||
Verification without hardware: both modules run in an ARM emulator against the
|
||||
same fake sensor (`scratchpad/difftest/`). 76,011 checks over init, ID, gain,
|
||||
exposure, FPS, orientation and the temperature black-level logic: zero
|
||||
mismatches. Four injected bugs were each caught (82 to 928 mismatches).
|
||||
|
||||
Deliberate difference: orientation. The vendor driver maps "no mirror/flip" to
|
||||
0x022c=3 and its app inverts mirror and flip for this board, so the picture is
|
||||
upright at the sensor's native readout. Here "no mirror/flip" is native readout.
|
||||
|
||||
## Pin map
|
||||
|
||||
| Resource | Pad | Use | majestic / script |
|
||||
|---|---|---|---|
|
||||
| GPIO 11 | SPI0_DI | IR-cut, opens filter (night) | `nightMode.irCutPin1` |
|
||||
| GPIO 80 | SAR_GPIO1 | IR-cut, closes filter (day) | `nightMode.irCutPin2` |
|
||||
| GPIO 23 | PM_IRIN | light board's day/night output: 1 day, 0 night | `nightMode.lightSensorPin`, `lightMonitor true` |
|
||||
| PWM4 / GPIO 9 | SPI0_CZ | IR lamp; driven as a GPIO, high at night | `nightMode.backlightPin 9` (`irLightPwmChannel 4` kept) |
|
||||
| PWM0 | PWM0 | white lamp | `nightMode.whiteLightPwmChannel` |
|
||||
| GPIO 12 | SPI0_DO | speaker amp enable | `audio.speakerPin` |
|
||||
| GPIO 10 | SPI0_CK | red/blue light IO, driven 1 at boot | `muxes.sh` |
|
||||
| GPIO 61 | SR_IO01 | warning-light output, active low; 1 (off) at boot | `muxes.sh` |
|
||||
| GPIO 60 | SR_IO00 | reset button, hold 5 s = factory reset | `mcl18d-io` |
|
||||
| GPIO 44 | FUART_CTS | alarm input, logged, runs `/etc/mcl18d/alarm-in` | `mcl18d-io` |
|
||||
| GPIO 45 | FUART_RTS | SD card power | device tree |
|
||||
| GPIO 22 | PM_SD_CDZ | SD card detect | device tree |
|
||||
| pad 48 | GPIO2 | audio amp (kernel `amp-pad`) | device tree |
|
||||
|
||||
## Build result
|
||||
|
||||
- uImage 1991 of 2048 KB, rootfs 5264 of 8192 KB (16 MB NOR layout).
|
||||
- The kernel's own SigmaStar checks passed: "The configuration of GPIO & PADMUX
|
||||
is correct!" and "PUSE check PASS!".
|
||||
- The DTB embedded in the uImage carries the MC-L18D pad mux and SD settings.
|
||||
- The rootfs has `sensor_gc5603_mipi.ko`, `/etc/sensors/gc5603.bin`, the
|
||||
`gc5603)` loader arm, `customizer.sh`, `muxes.sh`, `S94mcl18d`, `mcl18d-io`.
|
||||
- The shipped `sensor_gc5603_mipi.ko` passes the vendor comparison (0 of 76,011).
|
||||
- `ci-matrix.py --self-test` passes with the board and package registered.
|
||||
|
||||
## PTZ
|
||||
|
||||
The infinity6c majestic build has no PTZ settings, so majestic-af cannot load
|
||||
on this chip. PTZ instead goes through `onvif-simple-server` on port 85, whose
|
||||
PTZ hooks run `pelco-ptz`, which drives the lens board and any Pelco-D head on
|
||||
connector D7 (`/dev/ttyS2`, 57600 baud, address 1 by default; `/etc/pelco-ptz.conf`).
|
||||
majestic's own ONVIF is switched off on first boot so clients find one camera.
|
||||
|
||||
D7 is a 3.3 V UART. An RS-485 Pelco head needs a TTL-to-RS-485 adapter.
|
||||
|
||||
**The lens board must be kept awake.** It, and the pan/tilt it drives, ignore
|
||||
every Pelco-D frame unless autofocus data frames keep arriving, which the
|
||||
vendor firmware streams at frame rate. `S94mcl18d` runs `pelco-ptz keepalive`,
|
||||
one frame every 100 ms (`keepalive_ms` in `/etc/pelco-ptz.conf`; 0 turns it
|
||||
off). Without it nothing on D7 moves and nothing answers. Details and the
|
||||
measurements are in `AF-BOARD-PROTOCOL.md`, "What this means for OpenIPC".
|
||||
|
||||
| ONVIF | Pelco-D |
|
||||
|---|---|
|
||||
| ContinuousMove (pan, tilt, zoom, diagonals) | movement bits, one combined frame |
|
||||
| Set/Goto/RemovePreset, home | presets 2..32; preset 1 is home |
|
||||
| GetStatus | last commanded position: this head answers no position query |
|
||||
| AbsoluteMove, RelativeMove | not offered: this head ignores set-position (0x4B/0x4D/0x4F) |
|
||||
|
||||
The head's absolute positions are its presets, which it stores and returns to
|
||||
itself. `pelco-ptz abs`/`rel` remain for a head that implements the extended
|
||||
commands; uncomment `jump_to_abs`/`jump_to_rel` in `/etc/onvif.conf` for one.
|
||||
|
||||
Coordinates: pan -1..1 is -180..180 degrees, tilt -1..1 is -90..90 degrees (up
|
||||
positive, clamped to `tilt_min`/`tilt_max`), zoom 0..1 is wide..tele. Invert
|
||||
pan or tilt in `/etc/pelco-ptz.conf` for a ceiling mount.
|
||||
|
||||
ONVIF login is `root` with a random password until you run `onvif-passwd`.
|
||||
Use the camera's root password there: clients reuse the ONVIF credentials for
|
||||
RTSP, which majestic checks against root.
|
||||
|
||||
Upstream `onvif_simple_server` bugs fixed by the package patch: a pan/tilt
|
||||
AbsoluteMove also drove the zoom fully wide; zoom-only absolute and relative
|
||||
moves ran an uninitialised command; an empty RelativeMove was accepted; a
|
||||
missing Zoom space was passed to strcmp; SetPreset scanned `%s` into an int.
|
||||
|
||||
Tests, all host-native, in `anjvision-mcl18d/src/`:
|
||||
- `make test`: frames and coordinate mapping, byte for byte.
|
||||
- `make e2e`: the real `pelco-ptz` against a simulated head on a pty,
|
||||
including the focus and iris frames, and `keepalive`: whole frames at the
|
||||
configured rate, commands arriving intact between them, `keepalive_ms=0`.
|
||||
- `make af BUSYBOX=...`: `mcl18d-af` under a host build of the tree's busybox
|
||||
`ash`, against a simulated lens with backlash, noise and end stops. The
|
||||
cases cover starting on either side of focus, at focus, focus behind the
|
||||
start with snapshots that lag the lens, a refused crop, a wrong login and a
|
||||
featureless picture. The simulated lens moves while a sweep snapshots it.
|
||||
The bar is ending within one approach step of focus (15% in the sim's narrow
|
||||
bell); it passed 5 runs out of 5.
|
||||
- `tests/onvif_e2e.py`: SOAP requests through the patched server into
|
||||
`pelco-ptz` and the simulated head; 23 checks pass. The unpatched server
|
||||
fails 7 of them.
|
||||
|
||||
### Lens board: zoom, focus, autofocus
|
||||
|
||||
The AF/zoom lens board shares this port. The vendor runs the port at 57600
|
||||
baud whenever `/opt/ch/af.flag` exists, as it does on this camera, overriding
|
||||
its own 2400 PTZ setting. So `pelco-ptz.conf` defaults to 57600, and a pan/tilt
|
||||
head on the same wires has to be set to 57600 as well. The board takes plain
|
||||
Pelco-D for zoom, focus and iris, but only while `pelco-ptz keepalive` runs
|
||||
(above). An earlier version of this file said "115200
|
||||
baud, `FC 01` protocol"; that was wrong for this camera. See
|
||||
`AF-BOARD-PROTOCOL.md`.
|
||||
|
||||
```sh
|
||||
pelco-ptz move in 0.5; sleep 1; pelco-ptz stop # zoom
|
||||
pelco-ptz focus near; usleep 200000; pelco-ptz stop
|
||||
pelco-ptz iris open; usleep 200000; pelco-ptz stop
|
||||
mcl18d-af # autofocus once
|
||||
```
|
||||
|
||||
The focus and iris frames match the vendor's `FocusNearAutoOff` /
|
||||
`FocusFarAutoOff` / `IrisOpenAutoOff` / `IrisCloseAutoOff` byte for byte. Frames
|
||||
that move only the lens carry a speed in both data bytes, as the vendor sends them.
|
||||
|
||||
The board's own autofocus needs a frame of ISP focus statistics for every
|
||||
video frame, and neither majestic's API nor its plugins give them on this SoC
|
||||
(`/api/v1/isp/af-zones.json` answers "No AF statistics on this camera"); the
|
||||
keep-alive sends constant values, so focus after a zoom is not managed.
|
||||
`mcl18d-af` focuses from the camera side instead, once, when run.
|
||||
|
||||
It drives the focus motor with `pelco-ptz` and judges sharpness by the size of
|
||||
a full-frame JPEG snapshot (majestic answers `?crop=` with 501 here): a sharp
|
||||
picture of the bench was nearly three times the size of a blurred one. The
|
||||
motor is slow (focus lay up to 19 s of motor time away, and the sharp band
|
||||
was some 1.5 s wide), so it
|
||||
first sweeps with the motor running, snapshotting as it goes, until the
|
||||
picture has risen and fallen back (focus passed), turning round if it gets
|
||||
worse from the start. Then it backs off past the best snapshot and steps back
|
||||
in 150 ms steps the same way, stopping on the first worse step, so it never
|
||||
reverses near focus and gear backlash cannot leave it short. On the camera,
|
||||
from either side of focus: 12-27 s, ending at 99.4-99.6% of the best snapshot.
|
||||
It logs `AF_START`, `AF_SWEEP`, `AF_BACK`, `AF_STEP`, `AF_DONE`, `AF_NO_DETAIL`
|
||||
to syslog. It needs majestic's login: by default `/etc/onvif.conf`'s, which
|
||||
`onvif-passwd` sets to root's; otherwise `-u root:PASSWORD`. `mcl18d-af -h`
|
||||
lists `-s` (step), `-b` (back-off), `-t` (sweep limit) and the rest.
|
||||
|
||||
## On hardware, 2026-10-28/29
|
||||
|
||||
Seen on the camera, over serial and the network:
|
||||
|
||||
- Boots the 16 MB layout (`mtd3` 8192 KB); the sensor runs 2960x1666 and
|
||||
snapshots come out 2960x1664.
|
||||
- Pan, tilt and zoom move, from the shell and through ONVIF ContinuousMove and
|
||||
Stop on port 85, with the keep-alive running, after a reboot with nothing
|
||||
run by hand. Presets: set, move away, go to returns to the stored view.
|
||||
- The head never answers Pelco-D position queries and ignores set-position,
|
||||
also after "set zero" (0x49).
|
||||
- `/image.jpg?crop=` and `?width=` answer 501 on this platform.
|
||||
- A still scene's JPEG size holds within 0.1-0.6% between snapshots.
|
||||
- The heat sink was loose: the SoC ran at 76 C, the camera reset ("HW Reset"
|
||||
in the boot ROM, also idle in U-Boot), its memory self-test failed, the
|
||||
kernel oopsed on corrupted memory, and frames flared into coloured noise every
|
||||
5-15 s. With it refitted: 63 C steady, no reset or oops in the 25 minutes before I next rebooted it,
|
||||
and flares only at start-up and about one a minute after.
|
||||
|
||||
- Night mode: with `lightMonitor` on, majestic follows GPIO 23 (source 1),
|
||||
opens the IR-cut and goes grey at night, and drives GPIO 9 high; checked by
|
||||
inverting the sensor for a moment. GPIO 23 itself read 1 (day) with the
|
||||
room lights on and off, and nothing lit the scene with the IR line high or
|
||||
low, or with PWM4 at 0% or 100%. In the vendor's "Passive" mode, the one
|
||||
this unit shipped in, the board switches its IR LEDs and IRDET from its own
|
||||
photoresistor, so both wait for real darkness at that sensor, or the board
|
||||
is unpowered. Not confirmed either way.
|
||||
- Colour flares are still there after the heat sink fix, rarer: a horizontal
|
||||
line below which the frame is random noise, at random rows, mostly within
|
||||
seconds of a large lighting change. Not caused by UART traffic, by the
|
||||
driver's black-level writes, by motors, or by mid-frame writes of the frame
|
||||
length, gain index or analog gain page; the cause is open.
|
||||
- `set_gpio(12, 0) error` at every majestic start: the speaker-enable pin is
|
||||
not taken. Not looked into.
|
||||
|
||||
Not yet checked: GPIO 10/61's effect, SD card, audio in and out.
|
||||
|
||||
Flashing: the vendor U-Boot (the stock image's) stops on Enter, not Ctrl-C, and
|
||||
only within a very short window at power-on; `bootdelay=1` in this tree's
|
||||
environment gives OpenIPC's U-Boot a usable one.
|
||||
|
||||
## Upstreaming
|
||||
|
||||
This is a local port. Per `firmware/CLAUDE.md` it would be split across
|
||||
OpenIPC/sensors (driver), OpenIPC/linux (device tree) and OpenIPC/builder (the
|
||||
board files). Two pieces would not be accepted as they are: the driver's register
|
||||
tables come from the vendor module, and `gc5603.bin` is a binary from the factory
|
||||
image.
|
||||
@@ -0,0 +1,319 @@
|
||||
# OpenIPC on the AnjoyVision MC-L18D
|
||||
|
||||
A port of [OpenIPC](https://openipc.org) to the AnjoyVision MC-L18D:
|
||||
- SoC: SigmaStar SSC377D (Infinity6C), a copy of SigmaStar's SSC027A-S01A reference board;
|
||||
- sensor: GalaxyCore GC5603;
|
||||
- flash: 16 MB SPI NOR;
|
||||
- optional extras on connector D7: a zoom/focus lens board and a Pelco-D pan/tilt head.
|
||||
|
||||
This repository holds the reverse-engineering notes and tools, the built image, and
|
||||
the changes to OpenIPC's repositories. Those repositories are submodules pinned to
|
||||
their upstream commits, and the changes to each one are a patch in `patches/`.
|
||||
|
||||
This README walks through how the port was done, in order. Each step links to the
|
||||
document that covers it in depth.
|
||||
|
||||
---
|
||||
|
||||
## Status
|
||||
|
||||
**Works on the camera:**
|
||||
- boots OpenIPC from the 16 MB layout;
|
||||
- GC5603 video at 2960x1666 through majestic (RTSP, web UI, snapshots);
|
||||
- pan, tilt, zoom, focus and iris from the shell (`pelco-ptz`) and over ONVIF on port 85 (ContinuousMove, Stop, presets);
|
||||
- one-shot autofocus (`mcl18d-af`): 12–27 s, ending at 99.4–99.6% of the sharpest snapshot seen;
|
||||
- night-mode switching: majestic follows the light board's GPIO 23 and drives the IR-cut and IR lamp pins.
|
||||
|
||||
**Open:**
|
||||
- rare colour flares (a frame fills with noise below a random row), cause unknown;
|
||||
- the light board's IR LEDs never lit during testing;
|
||||
- the head only takes presets, so ONVIF AbsoluteMove and RelativeMove are not offered;
|
||||
- the lens board's own autofocus can't run, because majestic doesn't export the ISP's AF statistics on this chip;
|
||||
- SD card, audio and GPIO 10/61 not yet checked on hardware.
|
||||
|
||||
---
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| `firmware/` | submodule: [OpenIPC/firmware](https://github.com/OpenIPC/firmware) at 7d213e9. Its patch adds the board, the sensor driver, the board package and the ONVIF fixes. **This is the only tree you need to build.** |
|
||||
| `sensors/` | submodule: [OpenIPC/sensors](https://github.com/OpenIPC/sensors). Its patch adds `sigmastar/infinity6c/sensor_gc5603_mipi.c` |
|
||||
| `linux-infinity6c/` | submodule: [OpenIPC/linux](https://github.com/OpenIPC/linux), branch `sigmastar-infinity6c`. Its patch adds the MC-L18D device tree. About 1.3 GB |
|
||||
| `onvif_simple_server/` | submodule: [roleoroleo/onvif_simple_server](https://github.com/roleoroleo/onvif_simple_server). Its patch fixes PTZ bugs |
|
||||
| `ipctool/`, `majestic-af/` | submodules, reference only, no changes |
|
||||
| `patches/` | `<submodule>.patch` for each submodule with changes, and `export.sh`, which regenerates them |
|
||||
| `images/` | the built firmware: `openipc.ssc377d-nor-lite.tgz`, `uImage.ssc377d`, `rootfs.squashfs.ssc377d` |
|
||||
| `af-board-re/` | lens-board protocol tools: ARM emulator, PLT and literal-pool resolvers, `verify.py` |
|
||||
| `gc5603-difftest/` | differential test running the vendor's and the rebuilt sensor driver side by side |
|
||||
| `builder/Dockerfile` | the Ubuntu 24.04 build container |
|
||||
| `LEARNING-GUIDE.md` | the whole port: sources for every fact, every change, tests, mistakes |
|
||||
| `MCL18D-PORT.md` | short port notes and pin map |
|
||||
| `TECH-SPEC.md` | specification: interfaces, configs, protocols, algorithms, verification matrix |
|
||||
| `AF-BOARD-PROTOCOL.md` | the lens-board serial protocol, byte by byte |
|
||||
| `CODE-CHANGES.md` | every changed file, in full |
|
||||
|
||||
**Not in this repository:** the vendor's firmware. The RE steps start from a 16 MB
|
||||
flash dump of the camera (`backup-ssc377d-nor16m.bin`) and the vendor's update file
|
||||
(`r1885__firmware_MCL18D_V0-A-H5_V3.6.1.3_*.bin`). Both are the vendor's binaries, and
|
||||
the dump also carries the unit's MAC address. The tools expect them unpacked next to
|
||||
this checkout, as `../flash_dump_ssc377d/` and `../firmware_MCL18D_V3.6.1.3/`.
|
||||
|
||||
---
|
||||
|
||||
## Getting the sources
|
||||
|
||||
```sh
|
||||
git clone ssh://gitea@winslowthehedgehog.com/thebears/mcfl18d_openipc_re.git
|
||||
cd mcfl18d_openipc_re
|
||||
|
||||
# Enough to build: the firmware patch carries the other trees' changes as Buildroot patches
|
||||
git submodule update --init firmware
|
||||
git -C firmware apply ../patches/firmware.patch
|
||||
|
||||
# Everything (linux-infinity6c is a large download)
|
||||
git submodule update --init
|
||||
for p in patches/*.patch; do git -C "$(basename "$p" .patch)" apply "../$p"; done
|
||||
```
|
||||
|
||||
The changes stay uncommitted in each submodule, so `git -C firmware status` shows them.
|
||||
After changing a submodule, run `patches/export.sh` to rewrite its patch, then commit
|
||||
the patch here.
|
||||
|
||||
---
|
||||
|
||||
## How it was done
|
||||
|
||||
### 1. Learn how OpenIPC builds an image
|
||||
|
||||
You need this picture before any of the changes make sense
|
||||
([guide §2](LEARNING-GUIDE.md#2-how-openipc-builds-an-image-the-mental-model)):
|
||||
- OpenIPC firmware is a Buildroot external tree. `make BOARD=x` picks `br-ext-chip-<vendor>/configs/x_defconfig`.
|
||||
- The kernel comes from OpenIPC/linux as a tarball. On SigmaStar the device tree is chosen by the kernel option `CONFIG_SS_DTB_NAME`, so a new board needs a new `.dts` and a kernel config that names it.
|
||||
- Sensor drivers are separate modules built from OpenIPC/sensors. At boot `load_sigmastar` loads the one named in the U-Boot variable `sensor`.
|
||||
- majestic, the closed-source streamer, needs an IQ (tuning) file per sensor and reads `/etc/majestic.yaml`.
|
||||
- Per-board settings go in sanctioned hooks, `customizer.sh` and `muxes.sh`, never in shared files.
|
||||
|
||||
### 2. Take the vendor firmware apart
|
||||
|
||||
([guide §3](LEARNING-GUIDE.md#3-taking-the-vendor-firmware-apart))
|
||||
|
||||
**The update file.** `binwalk` and `xxd` show a 1556-byte vendor header (`ANJOY888`),
|
||||
a uImage kernel and an xz SquashFS. The uImage header says LZMA but the payload is xz:
|
||||
trust the magic bytes, not the header.
|
||||
|
||||
```sh
|
||||
dd if=update.bin of=kernel.uImage bs=1 skip=1556 count=$((1899576+64))
|
||||
dd if=kernel.uImage of=kernel.xz bs=64 skip=1
|
||||
xz -dc kernel.xz > kernel.img
|
||||
dd if=update.bin of=rootfs.squashfs bs=1 skip=1901196 count=8897236
|
||||
unsquashfs -d rootfs rootfs.squashfs
|
||||
```
|
||||
|
||||
To get the device tree, search `kernel.img` for the DTB magic `D0 0D FE ED`, keep the
|
||||
candidate whose `totalsize` field makes sense, carve it out and decompile it with
|
||||
`dtc -I dtb -O dts`.
|
||||
|
||||
**The flash dump.** The U-Boot environment's `mtdparts` gives the partitions: BOOT
|
||||
192 KB, kernel 2 MB, rootfs 0xCD0000, DATA 1 MB (jffs2, unpacked with `jefferson`).
|
||||
The kernel and sensor driver match the update file. DATA holds the live settings
|
||||
(`config.xml`): lens board on, Pelco-D on COM1. **Keep the dump. It is the only way
|
||||
back to stock.**
|
||||
|
||||
**Where the vendor's logic lives:** `libtools.so` (board tables), `media_server`
|
||||
(video, ISP, lamps, AF data), `comm_server` (serial: PTZ, lens board, upgrade),
|
||||
`gc5603_MIPI_1125.ko` (sensor), `gc4023_day.bin` (the IQ file this board really runs).
|
||||
The tools were `strings`, `objdump`, `radare2`, `unicorn`, `pyelftools`, `dtc` and
|
||||
`jefferson`.
|
||||
|
||||
### 3. Map the hardware
|
||||
|
||||
([guide §4](LEARNING-GUIDE.md#4-hardware-facts-and-their-sources), pin map in
|
||||
[MCL18D-PORT.md](MCL18D-PORT.md#pin-map))
|
||||
|
||||
The app stores no pin numbers as strings. Find `gpio_init_by_array`, follow its caller
|
||||
to the array for this board (device type 0x681), and decode each entry's type code
|
||||
from the getter functions that read it (the reset-button getter looks for type 3, and
|
||||
so on). Name each pin by what its consumer does with it, not by where it sits in the
|
||||
table. The IR-cut pins and the light sensor come from the vendor kernel's `/dev/irled`
|
||||
driver, and their direction from disassembling `media_server`'s day/night functions.
|
||||
|
||||
### 4. Kernel: the device tree
|
||||
|
||||
([guide §5](LEARNING-GUIDE.md#5-kernel-the-device-tree), patch:
|
||||
`patches/linux-infinity6c.patch`)
|
||||
|
||||
1. Compile OpenIPC's own `infinity6c-ssc027a-s01a.dts`.
|
||||
2. Decompile it and the vendor's DTB with `dtc -s` (sorted), and diff node by node.
|
||||
3. Decode the padmux entries into the kernel's macro names.
|
||||
|
||||
The differences: the white lamp, IR lamp and Ethernet LED pads, the 2-wire FUART to
|
||||
connector D7, and slower SD card settings. The new DTS `#include`s the reference DTS
|
||||
and overrides only `padmux` and `sdmmc`, so upstream fixes still flow in. The kernel
|
||||
build's own checks pass ("The configuration of GPIO & PADMUX is correct!").
|
||||
|
||||
### 5. Rebuild the GC5603 sensor driver
|
||||
|
||||
([guide §6](LEARNING-GUIDE.md#6-the-gc5603-sensor-driver), patch: `patches/sensors.patch`)
|
||||
|
||||
The vendor's `.ko` can't be loaded on OpenIPC. Its `ms_cus_sensor` struct lacks
|
||||
OpenIPC's SPI fields and two frame-sync fields, so every callback pointer sits 24 bytes
|
||||
off. That was measured with `offsetof` on OpenIPC's side and from the vendor's load
|
||||
offsets (`ldr r6, [r0, #0x40]`) on the other.
|
||||
|
||||
So the driver was rewritten:
|
||||
1. Disassemble the `.ko` with relocations, so calls and table references resolve to names.
|
||||
2. Generate the register tables (init, gain, exposure, VTS, mirror/flip) from its read-only data. Never hand-copy them.
|
||||
3. Recover the constants from the code: BG Bayer, 10-bit, 2-lane MIPI, 27 MHz MCLK, I2C 0x62, VTS 1750 at 30 fps.
|
||||
4. Keep the vendor's temperature-dependent black-level logic.
|
||||
5. Write it in OpenIPC's sensor-driver style (`sensor_gc5603_mipi.c`, about 950 lines).
|
||||
|
||||
**Verify without the camera** (`gc5603-difftest/`): `emu_ko.py` loads a kernel module
|
||||
into unicorn, applies its relocations, stubs the kernel and attaches a fake sensor
|
||||
that records every I2C transaction. `difftest.py` drives the vendor's module and the
|
||||
new one through init, gain and exposure sweeps, FPS, orientation and temperature
|
||||
levels, and compares every register write: 76,011 checks, 0 mismatches.
|
||||
|
||||
**Prove the test can fail.** Plant bugs and check they are caught. The first version
|
||||
missed two planted bugs in the temperature code because it never reached it. The fixed
|
||||
test catches all four (82 to 928 mismatches each).
|
||||
|
||||
There is no GC5603 IQ file in the dump. The vendor's `media_server` loads
|
||||
`gc4023_day.bin` for this board, so that file ships as `/etc/sensors/gc5603.bin`.
|
||||
|
||||
### 6. Register the board in OpenIPC
|
||||
|
||||
([guide §7](LEARNING-GUIDE.md#7-registering-the-board-in-the-openipc-tree), patch:
|
||||
`patches/firmware.patch`)
|
||||
|
||||
- `ssc377d_mcl18d_defconfig`: `ssc377d_lite` plus the board kernel config and DTS patch, 16 MB flash, `SNS_MODEL=gc5603`, the board package and `onvif-simple-server`.
|
||||
- `infinity6c-ssc027a-mcl18d.config`: the reference kernel config with `CONFIG_SS_DTB_NAME="infinity6c-ssc027a-s01a-mcl18d"`.
|
||||
- `load_sigmastar`: a new `gc5603)` case that loads `sensor_gc5603_mipi.ko`.
|
||||
- The DTS and the sensor driver go in as Buildroot patches generated from the other two submodules.
|
||||
- `ci-matrix.py` lists the board and package as not built by CI, so `--self-test` passes.
|
||||
|
||||
### 7. Write the board package
|
||||
|
||||
([guide §8](LEARNING-GUIDE.md#8-the-board-package-anjvision-mcl18d))
|
||||
|
||||
`firmware/general/package/anjvision-mcl18d/`:
|
||||
- **`customizer.sh`** (first boot): majestic's pin map (IR-cut 11/80, light sensor 23 with `lightMonitor true`, IR lamp on GPIO 9, white lamp PWM0, speaker 12), streams 2560x1440 + 640x360, majestic's ONVIF off, and a random ONVIF password.
|
||||
- **`muxes.sh`** (every boot): GPIO 10 and 61 high, as the vendor does.
|
||||
- **`S94mcl18d`**: starts `mcl18d-io`, `pelco-ptz keepalive` and ONVIF discovery.
|
||||
- **`mcl18d-io`**: reset button (hold 5 s for a factory reset) and alarm input.
|
||||
- **`pelco-ptz`** (C): Pelco-D for the head and lens board.
|
||||
- **`mcl18d-af`**: one-shot autofocus.
|
||||
|
||||
### 8. PTZ over ONVIF
|
||||
|
||||
([guide §9](LEARNING-GUIDE.md#9-ptz-over-onvif), patch: `patches/onvif_simple_server.patch`)
|
||||
|
||||
OpenIPC's PTZ plugin (`majestic-af`) can't load here. Comparing majestic's strings
|
||||
across chip families shows the infinity6c build has no "motorized lens" settings, and
|
||||
majestic is closed source. So ONVIF goes through `onvif-simple-server` on port 85,
|
||||
whose PTZ hooks run `pelco-ptz`.
|
||||
|
||||
`pelco-ptz` keeps frame building (`pelco.c`, pure functions) apart from I/O (`main.c`),
|
||||
so tests pin every byte. It combines pan and tilt calls that arrive within 300 ms into
|
||||
one diagonal frame, stores presets, and serialises access with `flock`. Testing it
|
||||
against the real ONVIF server found six upstream bugs, among them an AbsoluteMove that
|
||||
drove the lens fully wide every time, an uninitialised buffer passed to `system()`,
|
||||
and memory corruption in SetPreset. They are fixed in
|
||||
`firmware/general/package/onvif-simple-server/03-ptz-absolute-relative-zoom-fixes.patch`.
|
||||
|
||||
### 9. Decode the lens board protocol
|
||||
|
||||
([guide §10](LEARNING-GUIDE.md#10-the-lens-board-zoom--focus-protocol), spec:
|
||||
[AF-BOARD-PROTOCOL.md](AF-BOARD-PROTOCOL.md), tools: `af-board-re/`)
|
||||
|
||||
- **Static reading** of `comm_server` and `media_server`. radare2 labels this binary's library calls one PLT entry off, so `plt.py` rebuilds the map from each stub's relocation. `od.py` resolves `movw`/`movt` pairs and literal pools.
|
||||
- **Emulation** (`emu.py`): run the vendor's own `HandleYuntai` PTZ dispatcher and AF senders in unicorn with libc stubbed, and record exactly what they `write()` to the UART.
|
||||
- **Follow the flags.** `FC 01` frames at 115200 baud are in the binary, but only for other customers' builds. With `af.flag` present, as on this camera, the link is `/dev/ttyS2` at 57600 8N1, plain Pelco-D at address 1, plus an 18-byte AF statistics frame (`CAfV2`) every video frame.
|
||||
- `verify.py` re-derives every frame in the spec from the binaries: 40/40 checks pass.
|
||||
|
||||
```sh
|
||||
python3 af-board-re/verify.py ../flash_dump_ssc377d
|
||||
```
|
||||
|
||||
### 10. Build
|
||||
|
||||
([guide §12](LEARNING-GUIDE.md#12-building))
|
||||
|
||||
Buildroot 2024.02's host `tar` doesn't build on Arch, so the build runs in the Ubuntu
|
||||
24.04 container from `builder/`. Build outside any synced folder.
|
||||
|
||||
```sh
|
||||
docker build -t openipc-builder:24.04 builder
|
||||
F=$PWD/firmware; O=~/.cache/openipc-mcl18d
|
||||
docker run --rm --user $(id -u):$(id -g) -e HOME=$O/home -e BR2_DL_DIR=$O/dl -e PWD=$F \
|
||||
-v $F:$F -v $O:$O -w $F openipc-builder:24.04 make BOARD=ssc377d_mcl18d TARGET=$O/output
|
||||
```
|
||||
|
||||
- `PWD` must be passed in, because the Makefile reads it and docker doesn't set it. Without it the build "finishes" instantly. Read the log, not the exit code.
|
||||
- The container needs `bsdextrautils` for `hexdump`. Without it the kernel's padmux check fails with a misleading `dtc` "Unable to parse input tree".
|
||||
- Result: uImage 1991 / 2048 KB, rootfs 5264 / 8192 KB.
|
||||
|
||||
### 11. Test on the host
|
||||
|
||||
([guide §13](LEARNING-GUIDE.md#13-testing-what-was-tested-and-how))
|
||||
|
||||
| Test | Result |
|
||||
|---|---|
|
||||
| `gc5603-difftest/` against the vendor driver | 76,011 checks, 0 mismatches; 4/4 planted bugs caught |
|
||||
| `make test` in `anjvision-mcl18d/src` (every Pelco-D frame byte for byte) | pass |
|
||||
| `make e2e` (`pelco-ptz` against a simulated head on a pseudo-terminal) | pass |
|
||||
| `tests/onvif_e2e.py` (ONVIF SOAP → patched server → `pelco-ptz` → simulated head) | 23/23; the unpatched server fails 7 |
|
||||
| `make af BUSYBOX=…` (`mcl18d-af`, comment-stripped as shipped, under the tree's own busybox `ash`, against a simulated lens) | 14/14 |
|
||||
| `af-board-re/verify.py` | 40/40 |
|
||||
| `ci-matrix.py --self-test`, shell parse and comment-strip tests | pass |
|
||||
|
||||
### 12. Flash and bring up on the camera
|
||||
|
||||
([guide §20](LEARNING-GUIDE.md#20-on-the-hardware-bring-up-2026-10-2829))
|
||||
|
||||
**Bench:** a 3.3 V USB serial adapter on UART0 at 115200, a TFTP server for the images,
|
||||
and a switchable plug to power-cycle the camera.
|
||||
|
||||
**Getting into U-Boot:** the vendor's U-Boot ignores Ctrl-C. It stops on Enter, and
|
||||
only in a very short window, so send Enter continuously from power-on.
|
||||
|
||||
**Flashing:** load each image to RAM over TFTP, check its `crc32` against the PC's,
|
||||
write everything except the boot area first, write the boot area last in one command
|
||||
line, then read back and compare. OpenIPC's U-Boot picks the rootfs size from the
|
||||
squashfs already in flash, so writing the larger rootfs is what moves the camera to
|
||||
the 16 MB layout.
|
||||
|
||||
**First claim:** root's password is set at the first login, which also accepts the
|
||||
majestic EULA. Only the camera's owner may do that.
|
||||
|
||||
What the hardware then showed, and what changed because of it:
|
||||
- **Resets and memory corruption were heat.** The boot ROM said `HW Reset` every time, which ruled out software. majestic's `/metrics` read 76 C. With the heat sink refitted: 63 C, no more resets.
|
||||
- **Nothing on D7 moved, though the bytes left the UART.** Replaying the rest of the vendor's traffic found it: the lens board, and the head behind it, ignore every command unless AF frames keep arriving. Five frames wake it, one frame every 100 ms keeps it awake. The vendor never noticed because it streams them from boot. Hence `pelco-ptz keepalive`.
|
||||
- **The head ignores Pelco-D set-position and never answers queries**, but presets work. So presets are its only absolute positions.
|
||||
- **Autofocus had to be redesigned.** The motor is slow (focus up to 19 s of travel away) and reports no position, and majestic refuses snapshot crops on this chip. `mcl18d-af` now judges sharpness by the size of a full-frame JPEG, sweeps with the motor running until focus has been passed, then approaches it from one side so gear backlash can't leave it short.
|
||||
- **Night mode needed `lightMonitor true`** before majestic would read the light sensor, and `backlightPin 9`, because this majestic brings up no PWM lamp on infinity6c.
|
||||
- **With no position feedback, the picture was the instrument:** mean pixel difference for "did it move", phase correlation for pan/tilt, a scale search for zoom, Laplacian variance for focus.
|
||||
|
||||
---
|
||||
|
||||
## Lessons
|
||||
|
||||
The guide lists 21 mistakes and how each was caught
|
||||
([§17](LEARNING-GUIDE.md#17-mistakes-made-and-corrected)). The ones that matter most:
|
||||
- A byte pattern in a binary means the code exists, not that your configuration uses it. Follow the flags.
|
||||
- Prove a test can fail before trusting it.
|
||||
- Reproduce everything the vendor puts on the wire, not just the part you think matters.
|
||||
- Diff device trees after normalising them (`dtc -s`), never as source.
|
||||
- Find tables through the functions that consume them.
|
||||
- Emulate branchy vendor code instead of reading it.
|
||||
- Test shell scripts under the shell they ship with, after the build has transformed them.
|
||||
- Measure the actuator before tuning a search for it.
|
||||
- On SigmaStar, a `devmem` read of the wrong register bank resets the SoC. Probe one bank before dumping many.
|
||||
|
||||
## Upstreaming
|
||||
|
||||
This is a local port. Upstream, the driver would go to OpenIPC/sensors, the device tree
|
||||
to OpenIPC/linux and the board files to OpenIPC/builder. Two parts would not be
|
||||
accepted as they are: the sensor's register tables come from the vendor module, and
|
||||
`gc5603.bin` is the vendor's IQ file. The onvif-simple-server fixes can go upstream as
|
||||
a pull request ([guide §15](LEARNING-GUIDE.md#15-upstreaming-what-openipc-would-and-would-not-accept)).
|
||||
+784
@@ -0,0 +1,784 @@
|
||||
# MC-L18D on OpenIPC: technical specification
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Device | AnjoyVision MC-L18D camera module |
|
||||
| SoC / sensor / flash | SigmaStar SSC377D (Infinity6C) / GalaxyCore GC5603 / 16 MB SPI NOR |
|
||||
| Firmware base | OpenIPC firmware tag `latest` (7d213e9), Buildroot 2024.02.10, Linux 5.10.61 |
|
||||
| Build target | `make BOARD=ssc377d_mcl18d` |
|
||||
| Document status | Describes the code as it stands, uncommitted on local branches. Nothing has run on the camera. |
|
||||
| Companion documents | `LEARNING-GUIDE.md` (how it was found and built), `AF-BOARD-PROTOCOL.md` (lens board wire protocol in full), `MCL18D-PORT.md` (short notes) |
|
||||
|
||||
**Evidence levels.** Every requirement or fact below is tagged with one of these:
|
||||
|
||||
| Tag | Meaning |
|
||||
|---|---|
|
||||
| **[V]** | Verified by a build, a test, or a check against the built image |
|
||||
| **[D]** | Derived from the vendor binaries: disassembly, emulation, or data tables |
|
||||
| **[A]** | Assumed; needs the camera to confirm |
|
||||
|
||||
---
|
||||
|
||||
## 1. Scope
|
||||
|
||||
### 1.1 In scope
|
||||
|
||||
- An OpenIPC image that boots on the MC-L18D with:
|
||||
- the GC5603 sensor;
|
||||
- the vendor's pin multiplexing;
|
||||
- night mode: IR-cut, CDS light sensor, IR and white lamps;
|
||||
- audio speaker enable;
|
||||
- SD card;
|
||||
- reset button;
|
||||
- alarm input.
|
||||
- ONVIF Profile S/T streaming with PTZ, served on port 85.
|
||||
- Control of the external devices on connector D7 (`/dev/ttyS2`):
|
||||
- the zoom/focus lens board: zoom, manual focus, iris;
|
||||
- a Pelco-D pan/tilt head: continuous, absolute and relative moves, presets, home, position.
|
||||
- A one-shot contrast autofocus, `mcl18d-af`.
|
||||
|
||||
### 1.2 Out of scope / not supported
|
||||
|
||||
| Item | Reason |
|
||||
|---|---|
|
||||
| The lens board's own autofocus | Needs per-frame ISP AF statistics. The closed-source majestic doesn't export them. [D] |
|
||||
| PTZ in majestic's web UI and majestic's ONVIF | The infinity6c majestic build has no "Motorized lens" settings, so `majestic-af` can't load. [D] |
|
||||
| Lens-board firmware upgrade | The protocol is decoded (section 9.6) but not implemented. It is risky. |
|
||||
| Detection-box forwarding to auto-tracking heads | Only partly decoded. [D] |
|
||||
| Wi-Fi | Not addressed by this port. The lite defconfig's wireless tools stay in the image; whether the board has a Wi-Fi module was not checked. |
|
||||
|
||||
---
|
||||
|
||||
## 2. System overview
|
||||
|
||||
```
|
||||
┌──────────────────────────── SSC377D ─────────────────────────────┐
|
||||
GC5603 ──MIPI 2L──▶│ sensor_gc5603_mipi.ko ─▶ ISP (IQ: /etc/sensors/gc5603.bin) │
|
||||
I2C1 @0x62 │ │ │
|
||||
│ majestic ──RTSP :554, HTTP :80, JPEG───────┼──▶ clients
|
||||
│ (night mode: GPIO 9/11/23/80, PWM0) │
|
||||
│ │
|
||||
│ httpd :85 ─CGI─▶ onvif_simple_server ─exec─▶ pelco-ptz ──┐ │
|
||||
│ wsd_simple_server (WS-Discovery) │ │
|
||||
│ mcl18d-af ──HTTP /image.jpg───────▶ majestic │ │
|
||||
│ └────────────exec──────────────────────▶ pelco-ptz ──┤ │
|
||||
│ ▼ │
|
||||
│ mcl18d-io (GPIO 60 reset, GPIO 44 alarm) /dev/ttyS2 FUART│
|
||||
└───────────────────────────────────────────────────────────┼───────┘
|
||||
│ D7 TX/RX, 3.3 V,
|
||||
│ 57600 8N1
|
||||
┌──────────────────────┴──────┐
|
||||
│ lens board (Pelco-D addr 1) │
|
||||
│ optional Pelco-D PT head │
|
||||
└─────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Hardware interface
|
||||
|
||||
### 3.1 Pins
|
||||
|
||||
GPIO numbers are Linux sysfs numbers and equal the pad index. The numbering is identical in the vendor kernel and OpenIPC's. [D]
|
||||
|
||||
| Signal | Pad | Linux | Dir | Owner in this port | Behaviour | Source |
|
||||
|---|---|---|---|---|---|---|
|
||||
| IR-cut A (filter open, night) | PAD_SPI0_DI | GPIO 11 | out | majestic `nightMode.irCutPin1` | Pulsed for night | [D] vendor `/dev/irled` + `media_server` |
|
||||
| IR-cut B (filter closed, day) | PAD_SAR_GPIO1 | GPIO 80 | out | majestic `nightMode.irCutPin2` | Pulsed for day | [D] |
|
||||
| Light board's day/night output (D5-1 CDSIN, vendor "IRDET") | PAD_PM_IRIN | GPIO 23 | in | majestic `nightMode.lightSensorPin`, `lightMonitor true` | A digital level: 1 day, 0 night. In the vendor's "Passive" IR-cut mode, this unit's, the light board decides from its own photoresistor | [D] `/dev/irled`, `media_server`. On the camera it read 1 in a lit and an unlit room; 0 never seen |
|
||||
| IR lamp | PAD_SPI0_CZ | PWM4 (mode 2), or GPIO 9 | out | majestic `nightMode.backlightPin 9`, high at night (`irLightPwmChannel 4` is also set) | The vendor's active modes hold PWM4 at 100% at night. This majestic brings up no PWM lamp on infinity6c. Wiring sheet labels D5-3 "PWM1" | [D] padmux, `media_server` |
|
||||
| White lamp | PAD_PWM0 | PWM0 (mode 1) | PWM | majestic `whiteLightPwmChannel 0` | | [D] padmux |
|
||||
| Speaker amp enable | PAD_SPI0_DO | GPIO 12 | out | majestic `audio.speakerPin` | Polarity [A] | [D] `libtools.so` |
|
||||
| Red/blue light IO (vendor "alarm out 1") | PAD_SPI0_CK | GPIO 10 | out | `muxes.sh` | Driven 1 every boot | [D] |
|
||||
| Warning light (vendor IO type 12, `GetLedBrGpioPort`) | PAD_SR_IO01 | GPIO 61 | out | `muxes.sh` | Active low: driven 1 (off) every boot; the vendor's `mainctrl` pulls it low on alarm. Not a light-board enable | [D] |
|
||||
| Reset button | PAD_SR_IO00 | GPIO 60 | in | `mcl18d-io` | Idle level sampled at start | [D] |
|
||||
| Alarm input | PAD_FUART_CTS | GPIO 44 | in | `mcl18d-io` | Idle level sampled at start | [D] |
|
||||
| SD power | PAD_FUART_RTS | GPIO 45 | out | kernel (padmux SDIO1_PWR) | | [D] DTS |
|
||||
| SD card detect | PAD_PM_SD_CDZ | pad 22 | in | kernel | | [D] DTS |
|
||||
| Ethernet LED | PAD_PWM1 | LED1 mode 2 | — | kernel / PHY | | [D] padmux |
|
||||
| Lens/PTZ UART | PAD_FUART_RX/TX | `/dev/ttyS2` | UART | `pelco-ptz` | 2-wire, no RTS/CTS | [D] |
|
||||
| Sensor I2C | PAD_I2C1_SCL/SDA | I2C1 | I2C | sensor driver | 0x62, 320 kHz | [D] |
|
||||
| Core voltage select | PAD_PM_GPIO4 | GPIO 30 | out | OpenIPC reference DTS | Switched by CPU frequency (the vendor holds it 0) | [D] |
|
||||
| Audio amp | GPIO2 | pad 48 | out | kernel `amp-pad` | | [D] DTS |
|
||||
|
||||
### 3.2 Connectors
|
||||
|
||||
From the vendor wiring sheet:
|
||||
|
||||
| Connector | Pins used |
|
||||
|---|---|
|
||||
| D1 | pin 7 reset, pin 8 network LED |
|
||||
| D5 | 1 CDS in, 3 IR lamp PWM, 4 white lamp PWM |
|
||||
| D6 | IR-cut coil |
|
||||
| D7 | TX, RX (3.3 V TTL), 4 SPKEN, 5 red/blue IO |
|
||||
|
||||
**Requirement:** a Pelco-D head with an RS-485 input needs a TTL↔RS-485 adapter on D7. [A]
|
||||
|
||||
### 3.3 Flash layout
|
||||
|
||||
**Vendor layout** (from the dump's `mtdparts`): [D]
|
||||
- `0x30000(BOOT)`, `0x200000(kernel)`, `0xCD0000(rootfs)`, `0x100000(DATA)`
|
||||
|
||||
**OpenIPC 16 MB NOR layout**, enforced by `CHECK_SIZE`: [V]
|
||||
- kernel slot 2048 KB;
|
||||
- rootfs slot 8192 KB;
|
||||
- the remainder is overlay (jffs2) and the U-Boot environment.
|
||||
|
||||
**Requirement:** flashing needs OpenIPC's U-Boot for SSC377D and a serial console. The vendor dump (`backup-ssc377d-nor16m.bin`, MAC `F0:00:06:14:73:FF`) is the only recovery image.
|
||||
|
||||
---
|
||||
|
||||
## 4. Kernel
|
||||
|
||||
### 4.1 Source and config
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Source | `openipc/linux` tarball, branch `sigmastar-infinity6c` (`OPENIPC_KERNEL`) |
|
||||
| Config | `br-ext-chip-sigmastar/board/infinity6c/infinity6c-ssc027a-mcl18d.config` = `infinity6c-ssc027a.config` with `CONFIG_SS_DTB_NAME="infinity6c-ssc027a-s01a-mcl18d"` |
|
||||
| Patch dir | `br-ext-chip-sigmastar/board/infinity6c/mcl18d/linux/` (`BR2_LINUX_KERNEL_PATCH`) |
|
||||
| Patch | `0001-arm-dts-infinity6c-add-anjvision-mc-l18d.patch`: adds the DTS below |
|
||||
|
||||
### 4.2 Device tree: `infinity6c-ssc027a-s01a-mcl18d.dts`
|
||||
|
||||
`#include "infinity6c-ssc027a-s01a.dts"`, then overrides two nodes.
|
||||
|
||||
**`/soc/padmux/schematic`** (complete replacement):
|
||||
|
||||
| Pad | Mode | Purpose |
|
||||
|---|---|---|
|
||||
| GPIO_NR | UNKNOWN | NA (list terminator, as in the reference) |
|
||||
| PAD_PWM0 | PWM0_MODE_1 | PWM0 |
|
||||
| PAD_SPI0_CZ | PWM4_MODE_2 | PWM4 |
|
||||
| PAD_PWM1 | LED1_MODE_2 | ETH1_LED |
|
||||
| PAD_FUART_RX / TX | FUART_2W_MODE_1 | FUART_RX / TX |
|
||||
| PAD_I2C1_SCL / SDA | I2C1_MODE_1 | I2C1 |
|
||||
| PAD_SD_D0..D3, CLK, CMD | SD0_MODE_1 | SDIO1_* |
|
||||
| PAD_FUART_RTS | GPIO_MODE | SDIO1_PWR |
|
||||
| PAD_PM_SD_CDZ | SD0_CDZ_MODE_1 | SDIO1_CDZ |
|
||||
|
||||
**`/soc/sdmmc`:**
|
||||
- `slot-max-clks = 20000000` ×3
|
||||
- `slot-clk-driving`, `slot-cmd-driving`, `slot-data-driving = 0` ×3
|
||||
|
||||
**Acceptance:**
|
||||
- the kernel build prints "The configuration of GPIO & PADMUX is correct!" and "PUSE check PASS!"; [V]
|
||||
- the padmux table compiled into the uImage matches the vendor DTB's entry for entry. [V]
|
||||
|
||||
### 4.3 Not carried over
|
||||
|
||||
| Vendor feature | Disposition |
|
||||
|---|---|
|
||||
| The vendor's built-in `/dev/irled` driver | Replaced by majestic driving GPIO 11/80/23 directly |
|
||||
| GPIO 30 held 0 | OpenIPC reference behaviour kept |
|
||||
|
||||
---
|
||||
|
||||
## 5. Sensor driver: `sensor_gc5603_mipi.ko`
|
||||
|
||||
### 5.1 Packaging
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Source | `openipc/sensors` branch `gc5603-infinity6c`, `sigmastar/infinity6c/sensor_gc5603_mipi.c` (954 lines) |
|
||||
| Delivered by | `general/package/sigmastar-osdrv-sensors/0001-sigmastar-infinity6c-add-gc5603-driver.patch` |
|
||||
| Installed as | `/lib/modules/5.10.61/sigmastar/sensor_gc5603_mipi.ko` [V] |
|
||||
| Loaded by | `load_sigmastar`, `gc5603)` arm: `insmod sensor_gc5603_mipi.ko chmap=1`, chosen by the U-Boot env `sensor`, default `BR2_OPENIPC_SNS_MODEL="gc5603"` |
|
||||
| Model id string | `gc5603_MIPI` |
|
||||
|
||||
### 5.2 Interface parameters
|
||||
|
||||
All [D] from `gc5603_MIPI_1125.ko`.
|
||||
|
||||
| Parameter | Value |
|
||||
|---|---|
|
||||
| Bus | MIPI CSI-2, 2 lanes, CSI clock 216 MHz, long packet type 0x1C00, `PACKET_HEADER_EDGE1` |
|
||||
| Format | RAW10, Bayer BG, `CUS_SEN_10TO12_9000`, ISP_EXT |
|
||||
| Resolution | one mode: 2960×1666, 5–30 fps |
|
||||
| MCLK | 27 MHz |
|
||||
| I2C | address 0x62 (8-bit form), 320 kHz, 16-bit register / 8-bit data |
|
||||
| Chip ID | 0x03F0 = 0x56, 0x03F1 = 0x03 (ID 0x5603); 3 read attempts |
|
||||
| Polarities | PWDN positive, RESET negative, VSYNC/HSYNC negative, PCLK positive |
|
||||
| Power-on | PWDN inactive, RESET active 1 ms, PWDN active 1 ms, RESET release 1 ms, MCLK on, wait 5 ms |
|
||||
| Init | 136 register writes, including one 20 ms delay (0xFFFF entry); each write retried up to 10× at 10 ms |
|
||||
| Line period | 19047 ns (HTS 0x04B0) |
|
||||
| VTS at 30 fps | 1750; `VTS = 1750·30 / fps` (fps in 5..30, or 5000..30000 as ×1000) |
|
||||
| Exposure | `lines = 1000·µs / 19047` (minimum 1). Registers 0x0202 (bits 13–8, masked 0x3F), 0x0203 (bits 7–0). VTS is extended to `lines + 8` when exposure exceeds `VTS − 8`. Registers 0x0340/0x0341. |
|
||||
| Exposure range reported | 30 µs .. 200,000 µs (1/5 s); shutter step = 1 line |
|
||||
| Gain | 1×..128× (×1024 units). 26-entry analog table, values 1024..63440: page 0x031D=0x2D, then 0x0614/0x0615/0x0225, then 0x031D=0x28, then 0x1467/0x1468/0x00B8/0x00B9. Digital gain = `gain·64 / analog`, capped at 128, written to 0x0064 = dgain>>6, 0x0065 = (dgain<<2)&0xFF. |
|
||||
| Delays | AE gain delay 2 frames, shutter delay 2 frames |
|
||||
| Register commit | Gain, exposure and VTS are written together on the next `CUS_FRAME_ACTIVE` notify, as are orientation changes (22 registers, 20 ms, then 3 post registers) |
|
||||
|
||||
**Temperature handling** (vendor logic, kept exactly):
|
||||
- On every gain set, it reads a level from 0x0410 (low) / 0x0414 (high).
|
||||
- By level (thresholds 5, 11, 27, 40, 51, 69, and high byte 1 with low > 32) and gain band (<16×, <32×, <64×, <80×, ≥80×), it writes a black-level trim to 0x0455/0x0456 (coarse) and 0x0451/0x0452 (fine).
|
||||
- While hot, it walks the usable analog table down to 17 entries (when level > 28), then back up (when level ≤ 15).
|
||||
- At level ≤ 5 it resets to the full table and trim (4, 0).
|
||||
- Gain below 8× clears the hot flag.
|
||||
|
||||
**Orientation** (deliberate difference from the vendor):
|
||||
|
||||
| ONVIF/majestic | Vendor 0x022C | This driver 0x022C / 0x0063 / 0x0A73 |
|
||||
|---|---|---|
|
||||
| M0F0 | 3 | 0 / 0 / 0x60 |
|
||||
| M1F0 | 2 | 1 / 1 / 0x61 |
|
||||
| M0F1 | 1 | 2 / 2 / 0x62 |
|
||||
| M1F1 | 0 | 3 / 3 / 0x63 |
|
||||
|
||||
The vendor's application inverts both mirror and flip on this board, so the vendor's displayed default is native readout. Here M0F0 *is* native readout. Whether that is upright is [A].
|
||||
|
||||
### 5.3 Conformance
|
||||
|
||||
- **Differential emulation** (`openipc/gc5603-difftest/`) against the vendor module, same fake sensor. Covers init, ID, gain and exposure sweeps, FPS, orientation through the remap, and temperature levels:
|
||||
- 76,011 checks, 0 mismatches, including on the `.ko` built into the image; [V]
|
||||
- 4 of 4 injected faults detected (82–928 mismatches each). [V]
|
||||
- Loads and streams on the camera: [A]
|
||||
|
||||
### 5.4 IQ file
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Installed as | `/etc/sensors/gc5603.bin` (from `sigmastar-osdrv-infinity6c/files/sensor/configs/gc5603.bin`) |
|
||||
| Content | Byte-identical to the vendor's `/config/iqfile/gc4023_day.bin`, which the vendor `media_server` loads for this sensor on this board [D][V] |
|
||||
| Night IQ | Not shipped. The vendor also has `gc4023_night.bin`; majestic uses one file. |
|
||||
|
||||
---
|
||||
|
||||
## 6. Board package `anjvision-mcl18d`
|
||||
|
||||
### 6.1 Build integration
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Path | `general/package/anjvision-mcl18d/` |
|
||||
| Symbol | `BR2_PACKAGE_ANJVISION_MCL18D` |
|
||||
| Depends on | `BR2_PACKAGE_SIGMASTAR_OSDRV_INFINITY6C` |
|
||||
| Selects | `BR2_PACKAGE_ONVIF_SIMPLE_SERVER` |
|
||||
| Source | `SITE = $(PKGDIR)/src`, `SITE_METHOD = local`, license MIT |
|
||||
| Build | `make pelco-ptz` with the target toolchain; `CFLAGS -Os -Wall -Wextra`, `-lm` |
|
||||
| Registration | `general/package/Config.in` source line. `.github/scripts/ci-matrix.py`: `NOT_BUILT` += `anjvision-mcl18d`; `UNBUILT_BOARDS` += `ssc377d_mcl18d` (reason: single retail device) |
|
||||
|
||||
### 6.2 Installed files
|
||||
|
||||
| Target path | Mode | Source | Section |
|
||||
|---|---|---|---|
|
||||
| `/usr/share/openipc/customizer.sh` | 644 | `files/customizer.sh` | 6.4 |
|
||||
| `/usr/share/openipc/muxes.sh` | 644 | `files/muxes.sh` | 6.5 |
|
||||
| `/etc/init.d/S94mcl18d` | 755 | `files/S94mcl18d` | 6.6 |
|
||||
| `/usr/sbin/mcl18d-io` | 755 | `files/mcl18d-io` | 6.7 |
|
||||
| `/usr/sbin/pelco-ptz` | 755 | built from `src/` | 8 |
|
||||
| `/usr/sbin/mcl18d-af` | 755 | `files/mcl18d-af` | 10 |
|
||||
| `/usr/sbin/onvif-passwd` | 755 | `files/onvif-passwd` | 7.3 |
|
||||
| `/etc/pelco-ptz.conf` | 644 | `files/pelco-ptz.conf` | 8.2 |
|
||||
| `/etc/onvif.conf.mcl18d` | 600 | `files/onvif.conf` | 7.2 |
|
||||
|
||||
**All shipped shell scripts:**
|
||||
- run under busybox `ash` (`CONFIG_ASH_BASH_COMPAT=y`);
|
||||
- are comment-stripped at build time;
|
||||
- call only applets and binaries present in the image. [V]
|
||||
|
||||
### 6.3 Boot sequence
|
||||
|
||||
| Order | Script | This port's action |
|
||||
|---|---|---|
|
||||
| S30 | `S30customizer` | First boot only (no `/etc/custom.ok`): run `customizer.sh`, then touch `/etc/custom.ok`. **Every** boot: run `muxes.sh`. |
|
||||
| S70 | `S70vendor` | `load_sigmastar -i` (vendor name from `ipcinfo -v`): SDK modules, then `sensor_gc5603_mipi.ko` |
|
||||
| S94 | `S94mcl18d` | Start `mcl18d-io`; start `wsd_simple_server` once the ONVIF interface has IPv4 |
|
||||
| S95 | `S95majestic` | majestic, using the pin map written at first boot |
|
||||
| S96 | `S96onvifserver` | Fills `firmware_ver`, `hardware_id`, `serial_num` in `/etc/onvif.conf`; busybox `httpd -p 85` serves `/var/www/onvif` CGI |
|
||||
|
||||
`firstboot` (`sysupgrade -n`) wipes the overlay, which removes `custom.ok`, so `customizer.sh` runs again on the next boot.
|
||||
|
||||
### 6.4 `customizer.sh` (first boot)
|
||||
|
||||
1. `cli -s` sets in `/etc/majestic.yaml`:
|
||||
- `.nightMode.irCutPin1 11`
|
||||
- `.nightMode.irCutPin2 80`
|
||||
- `.nightMode.lightSensorPin 23`, `.nightMode.lightMonitor true`
|
||||
- `.nightMode.backlightPin 9`
|
||||
- `.nightMode.irLightPwmChannel 4`
|
||||
- `.nightMode.whiteLightPwmChannel 0`
|
||||
- `.nightMode.irCut auto`, `.nightMode.backlight auto`, `.nightMode.whiteLight auto`
|
||||
- `.audio.speakerPin 12`
|
||||
- `.onvif.enabled false`
|
||||
- `.video0.size 2560x1440`
|
||||
- `.video1.enabled true`, `.video1.size 640x360`
|
||||
2. Generates an 18-hex-digit random password (`hexdump -n 9 /dev/urandom`).
|
||||
3. Writes `/etc/onvif.conf` = `/etc/onvif.conf.mcl18d` with `password=<random>`, mode 600.
|
||||
|
||||
**Night mode.** Without `lightMonitor true` majestic never reads GPIO 23 and stays in day mode; with it, `/metrics` shows `night_mode_source 1`. [V] `backlightPin 9` is the IR lamp's pad driven as a plain GPIO, high at night, because this majestic does not bring up PWM lamps on infinity6c; forcing night by inverting the sensor for a moment logged `set_gpio(9,1)`. [V]
|
||||
|
||||
**Pin roles.** `irCutPin1` is majestic's "opening" coil and `irCutPin2` the "closing" coil. Source: majestic-webui `ircut-scan.js`, `irCutPin1: opensWhenHigh, irCutPin2: closesWhenHigh`. [D]
|
||||
|
||||
### 6.5 `muxes.sh` (every boot)
|
||||
|
||||
For (10, 1) and (61, 1): export the GPIO if needed, set direction `out`, write the value. GPIO 10 is the red/blue light IO (vendor alarm output 1); GPIO 61 is an active-low warning light, and 1 is off. These are the vendor's boot levels (`libtools.so` `gpio_init_by_array`). [D]
|
||||
|
||||
### 6.6 `S94mcl18d`
|
||||
|
||||
| Command | Behaviour |
|
||||
|---|---|
|
||||
| `start` | `start-stop-daemon -S -b -m -p /var/run/mcl18d-io.pid -x /usr/sbin/mcl18d-io`; the same for `pelco-ptz keepalive` with `/var/run/pelco-keepalive.pid` (section 8.1). Then, in the background: wait up to 60 s for an IPv4 address on `ifs` (from `/etc/onvif.conf`), then run `wsd_simple_server -i <ifs> -x http://%s:<port>/onvif/device_service -m <model> -n <manufacturer> -p /var/run/wsd_simple_server.pid` |
|
||||
| `stop` | Stop all three and remove their pid files |
|
||||
| `restart` | `stop`, then `start` |
|
||||
|
||||
### 6.7 `mcl18d-io`
|
||||
|
||||
| Item | Behaviour |
|
||||
|---|---|
|
||||
| Poll | Every 100 ms (`usleep 100000`) |
|
||||
| Idle levels | Read once at start for GPIO 60 and GPIO 44 |
|
||||
| Reset | GPIO 60 away from idle for 50 consecutive ticks (5 s): log `RESET_BUTTON held 5 s…`, run `firstboot`. A release before 5 s logs `RESET_BUTTON released after N ms, ignored`. |
|
||||
| Alarm | Each change of GPIO 44: log `ALARM_IN active\|idle`; if `/etc/mcl18d/alarm-in` is executable, run it in the background with `active`/`idle` |
|
||||
| Start log | `IO_WATCH_STARTED reset idle=<v> alarm idle=<v>` (tag `mcl18d`) |
|
||||
|
||||
---
|
||||
|
||||
## 7. ONVIF
|
||||
|
||||
### 7.1 Server
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Upstream | `onvif-simple-server` package, `roleoroleo/onvif_simple_server` at 7c8672fe84a14dfdc02ba7fdb1f9f88074b2efc6 |
|
||||
| Patches | Package patches 01, 02, plus this port's **03-ptz-absolute-relative-zoom-fixes.patch** |
|
||||
| Serving | busybox `httpd` on port 85, CGI under `/var/www/onvif` |
|
||||
| Discovery | `wsd_simple_server` |
|
||||
| majestic ONVIF | Disabled (`.onvif.enabled false`) so discovery shows one device |
|
||||
|
||||
### 7.2 `/etc/onvif.conf` (from `onvif.conf.mcl18d`)
|
||||
|
||||
| Key | Value |
|
||||
|---|---|
|
||||
| model / manufacturer | `MC-L18D` / `OpenIPC` |
|
||||
| ifs / port | `eth0` / `85` |
|
||||
| scope | `onvif://www.onvif.org/Profile/Streaming`, `…/Profile/T` |
|
||||
| user / password | `root` / random until `onvif-passwd` |
|
||||
| Profile_0 | 2560×1440, `rtsp://%s/stream=0`, snapshot `http://%s/image.jpg`, H264 |
|
||||
| Profile_1 | 640×360, `rtsp://%s/stream=1`, snapshot `…/image.jpg?width=640&height=360`, H264 |
|
||||
| ptz | `1`; x −1..1, y −1..1, z 0..1 |
|
||||
| PTZ hooks | `get_position`, `is_moving`, `move_left/right/up/down/in/out %f`, `move_stop`, `move_preset %d`, `goto_home_position`, `set_preset %s`, `set_home_position`, `remove_preset %d`, `jump_to_abs %f %f %f`, `jump_to_rel %f %f %f`, `get_presets`, all mapped to `/usr/sbin/pelco-ptz …` |
|
||||
|
||||
**Requirement:** set the ONVIF password to root's password (`onvif-passwd`). Clients reuse the ONVIF credentials for RTSP, which majestic checks against root.
|
||||
|
||||
### 7.3 `onvif-passwd [PASSWORD]`
|
||||
|
||||
- Prompts with echo off when no argument is given.
|
||||
- Refuses an empty password (exit 1).
|
||||
- Rewrites `password=` in `/etc/onvif.conf` through a temp file, mode 600.
|
||||
- Logs `ONVIF_PASSWORD_CHANGED`.
|
||||
|
||||
### 7.4 Patch 03: behavioural changes to `ptz_service.c`
|
||||
|
||||
| # | Request | Before | After |
|
||||
|---|---|---|---|
|
||||
| 1 | AbsoluteMove with PanTilt only | Zoom passed as 0, so the lens went fully wide | Missing axes passed as `nan`, meaning leave them |
|
||||
| 2 | AbsoluteMove with Zoom only | Command never built | `jump_to_abs nan nan z`; range-checked (fault −7) |
|
||||
| 3 | RelativeMove with Zoom only | Uninitialised buffer passed to `system()` | `jump_to_rel 0 0 dz`; range-checked |
|
||||
| 4 | RelativeMove with neither | Ran the uninitialised buffer | Refused (−4, `InvalidTranslation`) |
|
||||
| 5 | RelativeMove Zoom without a `space` attribute | `strcmp(NULL)`, a crash | Removed |
|
||||
| 6 | FOV-space relative pan/tilt | Scaled by 360/180 | `dx/180·max_step_x`, `dy/90·max_step_y` |
|
||||
| 7 | SetPreset with PresetToken | `sscanf("%s")` into an int: memory corruption | `%d` |
|
||||
|
||||
**Acceptance:** `tests/onvif_e2e.py`, 23 checks. The patched build passes all 23; the unpatched build fails 7. [V]
|
||||
|
||||
---
|
||||
|
||||
## 8. `pelco-ptz`
|
||||
|
||||
### 8.1 Command line
|
||||
|
||||
One command per process. Exit status: **0** OK, **1** usage or argument error, **2** port, lock, write or preset-store failure.
|
||||
|
||||
| Command | Effect | Port needed |
|
||||
|---|---|---|
|
||||
| `move left\|right\|up\|down\|in\|out [SPEED]` | Continuous motion. SPEED 0..1, default 0.5. Pan/tilt speed 0 stops that axis. | yes |
|
||||
| `focus near\|far` | Focus motor runs until `stop` | yes |
|
||||
| `iris open\|close` | Iris runs until `stop` | yes |
|
||||
| `stop` | Clears all motion and sends the stop frame | yes |
|
||||
| `abs X Y Z` | Absolute move in generic space; `nan` leaves an axis | yes |
|
||||
| `rel DX DY DZ` | Query position, add the deltas, then absolute move. A delta of 0 or `nan` leaves the axis. | yes |
|
||||
| `position` | Prints `x,y,z` (4 decimals), from head replies or the last commanded position | yes |
|
||||
| `moving` | Prints `1` while any axis moves or within `settle_ms` of an abs/preset/home move, else `0` | no |
|
||||
| `home` / `sethome` | Go to / set preset `home_preset` | yes |
|
||||
| `preset list` | Prints `N=name,x,y,z` lines | no |
|
||||
| `preset set NAME` | Allocates the lowest free N in 2..`max_preset` (≠ home); stores the queried position | yes |
|
||||
| `preset goto N` / `preset remove N` | N in 1..255 | yes |
|
||||
| `keepalive` | Sends `pelco_af_frame()` every `keepalive_ms` until killed; takes no lock; reopens the port after a write error. Started by `S94mcl18d`. | yes |
|
||||
|
||||
On this camera's head `abs` and `rel` do nothing (section 9.5); they stay for a head that implements the extended commands. [V]
|
||||
|
||||
**Preset names:**
|
||||
- 1–64 bytes;
|
||||
- no whitespace, control characters, `,`, `=` or DEL.
|
||||
|
||||
### 8.2 Configuration: `/etc/pelco-ptz.conf`
|
||||
|
||||
Format: `key=value`; `#` comments.
|
||||
|
||||
| Key | Default (file / built-in) | Meaning |
|
||||
|---|---|---|
|
||||
| `port` | `/dev/ttyS2` | Serial device |
|
||||
| `baud` | `57600` / `57600` | One of 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200; anything else is refused (`PTZ_CONF_BAUD`) |
|
||||
| `address` | `1` | Pelco address 0..255; out of range logs `PTZ_CONF_ADDRESS` and falls back to 1 |
|
||||
| `pan_invert`, `tilt_invert` | `0` | Mirror the axis (ceiling mount) |
|
||||
| `tilt_min`, `tilt_max` | `-90`, `90` | Head's tilt travel in degrees, up positive |
|
||||
| `home_preset` | `1` | Preset used as ONVIF home |
|
||||
| `max_preset` | `32` | Highest preset for ONVIF, capped at 255 |
|
||||
| `settle_ms` | `3000` | How long abs/preset/home counts as "moving" |
|
||||
| `query_timeout_ms` | `300` | Wait for a position reply |
|
||||
| `keepalive_ms` | `100` | Interval of `keepalive`'s frames; 0 makes `keepalive` exit at once |
|
||||
|
||||
**57600 baud:** the vendor `comm_server` sets the port to 57600 whenever `/opt/ch/af.flag` exists, as it does on this camera, overriding its PTZ setting of 2400. [D] A pan/tilt head sharing D7 must also run at 57600.
|
||||
|
||||
### 8.3 Serial line
|
||||
|
||||
| Setting | Value |
|
||||
|---|---|
|
||||
| Mode | `O_RDWR\|O_NOCTTY\|O_NONBLOCK`, `cfmakeraw`, 8N1, `CLOCAL\|CREAD`, no RTS/CTS |
|
||||
| Write | One 7-byte write, then `tcdrain`; a short write is an error |
|
||||
| Read | Only for position queries: `tcflush` input, send, `poll`/`read` until a valid reply or `query_timeout_ms` |
|
||||
| `keepalive` | Same setup, then `O_NONBLOCK` cleared so each 18-byte `write()` lands whole; the tty's write lock keeps it from splitting a command frame from another process |
|
||||
|
||||
### 8.4 Frames (Pelco-D)
|
||||
|
||||
`FF addr c1 c2 d1 d2 sum`, where `sum = (addr + c1 + c2 + d1 + d2) mod 256`.
|
||||
|
||||
**Motion frame** (one frame carries the whole motion state):
|
||||
|
||||
| Bit | Field |
|
||||
|---|---|
|
||||
| c2 0x02 / 0x04 | right / left (after `pan_invert`) |
|
||||
| c2 0x08 / 0x10 | up / down (after `tilt_invert`) |
|
||||
| c2 0x20 / 0x40 | zoom tele / wide |
|
||||
| c2 0x80 | focus far |
|
||||
| c1 0x01 | focus near |
|
||||
| c1 0x02 / 0x04 | iris open / close |
|
||||
| d1 | pan speed when panning |
|
||||
| d2 | tilt speed when tilting |
|
||||
|
||||
When **neither pan nor tilt** moves but the lens does, d1 = d2 = the zoom speed (if zooming and non-zero), else `0x30`. This matches the vendor's frames to the lens board. [D][V]
|
||||
|
||||
**Speed mapping:**
|
||||
- `pelco_speed(v)` = 0 for v ≤ 0 or NaN;
|
||||
- 0x3F for v ≥ 1;
|
||||
- else `round(v·63)`, minimum 1.
|
||||
|
||||
**Reference frames** (byte-checked by `make test`):
|
||||
|
||||
| Command | Frame |
|
||||
|---|---|
|
||||
| stop | `FF 01 00 00 00 00 01` |
|
||||
| left 0.5 | `FF 01 00 04 20 00 25` |
|
||||
| zoom in 0.5 | `FF 01 00 20 20 20 61` |
|
||||
| focus near | `FF 01 01 00 30 30 62` (vendor `FocusNearAutoOff`) |
|
||||
| focus far | `FF 01 00 80 30 30 E1` (vendor `FocusFarAutoOff`) |
|
||||
| iris open | `FF 01 02 00 30 30 63` |
|
||||
| iris close | `FF 01 04 00 30 30 65` |
|
||||
| preset set / goto / clear n | `FF 01 00 03 00 nn` / `07` / `05` (+ sum) |
|
||||
| set pan / tilt / zoom | `FF 01 00 4B/4D/4F vH vL` (+ sum) |
|
||||
| query pan / tilt / zoom | `FF 01 00 51/53/55 00 00` (+ sum) |
|
||||
| replies accepted | `FF addr 00 59/5B/5D vH vL sum`, with noise before it skipped and the checksum checked |
|
||||
|
||||
### 8.5 Generic coordinate space
|
||||
|
||||
| Axis | Generic | Pelco value |
|
||||
|---|---|---|
|
||||
| Pan | x −1..1 = −180..180° (`pan_invert` negates) | hundredths of a degree 0..35999, wrapped |
|
||||
| Tilt | y −1..1 = −90..90°, up positive, clamped to `tilt_min..tilt_max` | Pelco counts down from the horizon: `hundredths(−up)` |
|
||||
| Zoom | z 0..1 | `round(z·65535)` |
|
||||
|
||||
**Relative-move arithmetic:**
|
||||
- pan wraps in (−1, 1];
|
||||
- tilt clamps to `tilt_min/90 .. tilt_max/90`;
|
||||
- zoom clamps to 0..1.
|
||||
|
||||
### 8.6 Continuous-move combining
|
||||
|
||||
- ONVIF sends a diagonal as separate per-axis calls.
|
||||
- Each axis (pan, tilt, zoom, focus, iris) keeps the time it was last set.
|
||||
- On each `move`/`focus`/`iris`:
|
||||
- an axis set more than **300 ms** earlier is cleared (it belongs to an earlier request);
|
||||
- the new axis is set;
|
||||
- one frame carrying all live axes is sent.
|
||||
|
||||
### 8.7 State, locking, persistence
|
||||
|
||||
| File | Content |
|
||||
|---|---|
|
||||
| `/tmp/pelco-ptz.lock` | `flock(LOCK_EX)` for the whole run, so frames never interleave |
|
||||
| `/tmp/pelco-ptz.state` | 17 fields: pan dir/speed/ms, tilt dir/speed/ms, zoom dir/speed/ms, focus dir/ms, iris dir/ms, x, y, z, busy-until-ms. Written via `.tmp` + rename. A malformed file resets the state. |
|
||||
| `/etc/pelco-ptz.presets` | `N=name,x,y,z` per line. Written via `.tmp` + rename. |
|
||||
|
||||
Negative zero is normalised before output.
|
||||
|
||||
### 8.8 Logging
|
||||
|
||||
syslog, ident `pelco-ptz`, `LOG_USER`. Tags:
|
||||
- `PTZ_ABSOLUTE`
|
||||
- `PTZ_CONF_ADDRESS`, `PTZ_CONF_BAUD`
|
||||
- `PTZ_HOME_SET`
|
||||
- `PTZ_LOCK_FAILED`
|
||||
- `PTZ_PORT_OPEN_FAILED`, `PTZ_PORT_SETUP_FAILED`
|
||||
- `PTZ_PRESET_FULL`, `PTZ_PRESET_REMOVED`, `PTZ_PRESET_SAVE_FAILED`, `PTZ_PRESET_SET`
|
||||
- `PTZ_WRITE_FAILED`
|
||||
|
||||
---
|
||||
|
||||
## 9. Lens board interface
|
||||
|
||||
Summary; the full detail is in `AF-BOARD-PROTOCOL.md`. Everything in this section is [D] from the vendor `comm_server`/`media_server`, confirmed by emulating the vendor code: `af-board-re/verify.py`, 40/40. [V]
|
||||
|
||||
### 9.1 Link
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Port | `/dev/ttyS2`, shared with any pan/tilt head |
|
||||
| Line | 57600 8N1 when `/opt/ch/af.flag` exists (true on this camera). `_WTD` builds use 115200; `/opt/ch/diy_baudrate` overrides. |
|
||||
| Address | Pelco address 1 |
|
||||
|
||||
### 9.2 Commands the board accepts
|
||||
|
||||
Plain Pelco-D, as in section 8.4: zoom, focus, iris, stop, presets, and pan/tilt for the head behind the board, but only while the board is awake (9.5). [V]
|
||||
|
||||
In the vendor firmware, focus and iris always carry `30 30`, and zoom carries the speed level mapped 0..10 → 0x05..0x37.
|
||||
|
||||
### 9.3 AF data stream (produced here only as a keep-alive)
|
||||
|
||||
- One frame per ISP frame, with focus values FV0 (whole frame) and FV1 (centre):
|
||||
- `FV = Σ stat[a][w] >> 6` over arrays {0,1,3,4};
|
||||
- sent as `(FV>>11)&FF, (FV>>3)&FF`.
|
||||
- This camera's setting (`AfConfig type=1`) uses `CAfV2`, 18 bytes:
|
||||
`51 01 04 78 01 11 | FV0 | FV1 | gain | class<<4|night | stat bytes | ircut | IR% | white% | sum`.
|
||||
- The factory default `type=2` uses `CAfV3`, 16 bytes.
|
||||
- `pelco-ptz keepalive` sends one CAfV2 frame with constant values every 100 ms: `51 01 04 78 01 11 12 34 08 00 01 30 12 34 00 00 00 a5`. [V]
|
||||
|
||||
### 9.4 Version query (vendor, at boot)
|
||||
|
||||
- Camera sends: `END D7` ×8 at 60 ms intervals, then `VER ED`.
|
||||
- Board reply: byte 3 = lens code (01–15, 20/21), byte 4 = variant, bytes 5–8 = BCD date.
|
||||
- Fallback: `EXVER 8A`.
|
||||
|
||||
Not implemented here.
|
||||
|
||||
### 9.5 Behaviour with no AF data
|
||||
|
||||
Measured on the camera, 2026-10-28/29. [V]
|
||||
|
||||
| Condition | Result |
|
||||
|---|---|
|
||||
| No AF frames since boot | Nothing on D7 moves; no byte comes back (rx 0); no version reply. Same at every baud 2400–115200, Pelco-D address 0/1 and Pelco-P |
|
||||
| One AF frame, then a command | Ignored |
|
||||
| Five AF frames 33 ms apart, then a command | Obeyed: pan, tilt, zoom, focus |
|
||||
| 3 s silence after a burst | Still obeyed |
|
||||
| 40 s silence | Asleep again |
|
||||
| One frame every 100 ms | Awake throughout |
|
||||
| First stream after sleep | About 20 s of large focus moves before it settles |
|
||||
| Pelco-D 0x4B/0x4D/0x4F (also after 0x49) | Ignored |
|
||||
| Pelco-D 0x51/0x53/0x55 | Never answered |
|
||||
| Presets 0x03/0x07 | Work: go to returns to the stored view |
|
||||
| Board to camera | `51 01 04 78 01 0a … sum` while something moves; byte 10 tracks zoom (INFERRED); silent when idle |
|
||||
|
||||
### 9.6 Upgrade (vendor; not implemented)
|
||||
|
||||
1. Camera sends `END` ×15, then `START` + BE32 size + sum.
|
||||
2. Board requests `DATA` + BE32 address + `80` + sum.
|
||||
3. Camera answers with 138-byte blocks.
|
||||
4. Board ends with `OK 9A`.
|
||||
|
||||
---
|
||||
|
||||
## 10. `mcl18d-af`: one-shot contrast autofocus
|
||||
|
||||
### 10.1 Command line
|
||||
|
||||
```
|
||||
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] [-h]
|
||||
```
|
||||
|
||||
| Option | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `-u` | `user:password` from `/etc/onvif.conf` | majestic HTTP login (curl `--anyauth`) |
|
||||
| `-c` | middle third of `cli -g .video0.size`; `full` if unreadable | Judged region, in snapshot pixels. majestic refuses it on this SoC, so in practice the full frame |
|
||||
| `-s` | 150 | Approach step, ms of motor run time |
|
||||
| `-b` | 1000 | Extra back-off past the best snapshot before the approach, ms |
|
||||
| `-n` | 2 | Snapshots averaged per approach measurement |
|
||||
| `-w` | 300 | Wait after each motor stop before measuring, ms |
|
||||
| `-g` | 5 | An approach step is better or worse only if sharpness changes by more than g/1000 |
|
||||
| `-t` | 45 | Longest sweep one way, seconds of motor time |
|
||||
| `-a` | `http://127.0.0.1/image.jpg` | Snapshot URL (`?crop=` appended unless `full`) |
|
||||
|
||||
`-s`, `-b`, `-n`, `-w`, `-g`, `-t` must be non-negative integers; `-n` and `-s` at least 1.
|
||||
|
||||
Fixed in the script: a sweep has found focus once the picture rose 50/1000 above its start and then fell 30/1000 below its best on two snapshots running; it turns round if, after at least 1.5 s and 3 snapshots, it has not risen 50/1000 and is 30/1000 below its start. At most 3 back-offs.
|
||||
|
||||
### 10.2 Sharpness measure
|
||||
|
||||
`S` = byte size of a JPEG snapshot, read with `curl -s -f -w %{size_download}`: one snapshot per point during a sweep, the mean of `n` during the approach. At a fixed quality, finer detail compresses less.
|
||||
|
||||
Measured on the camera, 2026-10-29 [V]:
|
||||
- a sharp snapshot of the bench was about 338 KB and a blurred one about 126 KB;
|
||||
- two snapshots of a still scene differ by 0.1–0.6%;
|
||||
- `?crop=` answers HTTP 501; the script logs `AF_CROP_REFUSED` and judges the full frame.
|
||||
|
||||
### 10.3 What the lens is like
|
||||
|
||||
| Fact | Consequence | Source |
|
||||
|---|---|---|
|
||||
| The motor reports no position | Positions are motor run time, measured with `/proc/uptime` (centiseconds) | [D] |
|
||||
| Focus lay up to 19 s of motor time from the start; the sharp band is about 1.5 s wide | Short steps from a blurred start change the picture less than the noise, so the search is a continuous sweep first | [V] |
|
||||
| A snapshot shows the lens a little after the fact | Just after a reversal the picture goes on getting worse; the second sweep never turns | [V] once made a second sweep give up at once |
|
||||
| Each reversal loses travel to gear backlash | The finish approaches focus from one side only | [A]; a back-and-forth climb ended short of focus |
|
||||
|
||||
### 10.4 Algorithm
|
||||
|
||||
1. **Start.** Measure. If that fails or returns 0 with a crop set, retry the full frame (`AF_CROP_REFUSED`); if that fails too, `AF_SNAPSHOT_FAILED`, exit 2. Log `AF_START`.
|
||||
2. **Sweep** `far`, allowed to turn, for up to `-t` s. Take one snapshot as the base, start the motor, then loop:
|
||||
- snapshot; its time is the midpoint of the request, from the motor start;
|
||||
- better than the best so far: it becomes the best, and its time is `peak`;
|
||||
- once the best has risen past the found threshold, two snapshots running below it by the drop threshold: stop, focus passed (`AF_SWEEP <dir> found`);
|
||||
- the turn rule of 10.1 met: stop (`AF_SWEEP <dir> getting worse`);
|
||||
- time out: stop (`AF_SWEEP <dir> no focus`).
|
||||
3. **Second sweep**, `near`, never turning: for the first sweep's run plus `-t` s if it turned, plus 2×`-t` s if it timed out.
|
||||
4. Neither found focus: `AF_NO_DETAIL`, exit 3.
|
||||
5. **Back off** the other way for (run − peak) + `-b` ms (`AF_BACK`).
|
||||
6. **Approach** in the sweep's direction: measure, then repeat pulse `-s` ms, wait `-w`, measure:
|
||||
- better (by `g`): keep going (`AF_STEP … better`);
|
||||
- same: keep going (`… same`);
|
||||
- worse after something was better: done; the lens rests one step past the sharpest point (`… worse`);
|
||||
- worse before anything was better: the back-off was too short. Back off another `-b` ms and approach again; after 3 back-offs, `AF_LOST`, exit 2;
|
||||
- at most 2×`-b`/`-s` + 10 steps, then done.
|
||||
7. Measure once more and log `AF_DONE sharpness=<S> best_seen=<S> steps=<n>`.
|
||||
|
||||
### 10.5 Outputs
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| stdout and syslog (tag `mcl18d-af`) | `AF_START sharpness=<S> region=<crop>`, `AF_SWEEP <dir> found best=<S> at <ms>ms, ran <ms>ms` / `getting worse after <ms>ms, turning` / `no focus in <ms>ms`, `AF_BACK <dir> <ms>ms`, `AF_STEP <dir> <ms>ms sharpness=<S> better\|same\|worse`, `AF_DONE …`, `AF_CROP_REFUSED`, `AF_SNAPSHOT_FAILED`, `AF_NO_DETAIL`, `AF_LOST` |
|
||||
| Exit 0 | Focus found |
|
||||
| Exit 1 | Usage error |
|
||||
| Exit 2 | Snapshot or `pelco-ptz` failure, or focus not found again (`AF_LOST`) |
|
||||
| Exit 3 | No detail to focus on |
|
||||
| Exit 130 | Interrupted |
|
||||
| Safety | `trap stop EXIT`: the focus motor is always stopped on exit |
|
||||
|
||||
### 10.6 Conformance
|
||||
|
||||
`make af BUSYBOX=<host busybox>` runs the comment-stripped script under busybox `ash` built from the tree's own source, against a simulated lens:
|
||||
- 0..1500 ms of travel, with end stops;
|
||||
- 15 ms backlash per reversal;
|
||||
- ±0.5% noise on a Gaussian sharpness curve of width 250;
|
||||
- optionally, snapshots that show the lens some ms late.
|
||||
|
||||
The simulated travel is far shorter than the camera's, so it runs with `-w 20 -t 3 -b 150 -s 30`.
|
||||
|
||||
| Case | Required | Result |
|
||||
|---|---|---|
|
||||
| Start below, above and at focus, and far out (4 cases) | Ends within 100 ms of focus; motor stopped | pass [V] |
|
||||
| Default region | Middle-third crop URL | pass [V] |
|
||||
| Snapshots 150 ms late, focus behind the start | Still found | pass [V] |
|
||||
| Crop refused | Falls back to the full frame and still converges | pass [V] |
|
||||
| Wrong login | Exit 2, motor untouched | pass [V] |
|
||||
| Featureless scene | Exit 3 `AF_NO_DETAIL` | pass [V] |
|
||||
| Non-numeric option | Exit 1 | pass [V] |
|
||||
|
||||
On the camera, 2026-10-29, with the defaults [V]: from either side of focus, 12–27 s, ending at 99.4–99.6% of the best snapshot seen.
|
||||
|
||||
---
|
||||
|
||||
## 11. Build
|
||||
|
||||
### 11.1 Defconfig `ssc377d_mcl18d_defconfig`
|
||||
|
||||
`ssc377d_lite_defconfig` plus:
|
||||
|
||||
```
|
||||
BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE=".../infinity6c-ssc027a-mcl18d.config"
|
||||
BR2_LINUX_KERNEL_PATCH=".../board/infinity6c/mcl18d/linux"
|
||||
BR2_OPENIPC_FLASH_SIZE="16"
|
||||
BR2_OPENIPC_SNS_MODEL="gc5603"
|
||||
BR2_PACKAGE_ANJVISION_MCL18D=y
|
||||
BR2_PACKAGE_ONVIF_SIMPLE_SERVER=y
|
||||
```
|
||||
|
||||
### 11.2 Build environment
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Container | Ubuntu 24.04 (`openipc-builder:24.04`): build-essential, bc, bison, flex, cpio, rsync, unzip, wget, python3, cmake, u-boot-tools, bsdextrautils (`hexdump`, which the kernel's padmux check needs) |
|
||||
| Command | `docker run --rm --user $(id -u):$(id -g) -e HOME=$O/home -e BR2_DL_DIR=$O/dl -e PWD=$F -v $F:$F -v $O:$O -w $F openipc-builder:24.04 make BOARD=ssc377d_mcl18d TARGET=$O/output` |
|
||||
| `PWD` | Must be passed; the Makefile reads it from the environment |
|
||||
| Output | `$O/output/images/openipc.ssc377d-nor-lite.tgz`, `uImage.ssc377d`, `rootfs.squashfs.ssc377d` (copied to `openipc/images/`) |
|
||||
|
||||
### 11.3 Size budget [V]
|
||||
|
||||
| Image | Used | Cap |
|
||||
|---|---|---|
|
||||
| uImage | 1991 KB | 2048 KB (57 KB headroom) |
|
||||
| rootfs (squashfs xz) | 5264 KB | 8192 KB |
|
||||
|
||||
---
|
||||
|
||||
## 12. Verification matrix
|
||||
|
||||
| ID | Requirement | Method | Status |
|
||||
|---|---|---|---|
|
||||
| V1 | Image builds and fits flash | Container build, `CHECK_SIZE` | [V] |
|
||||
| V2 | Padmux and pin use consistent | Kernel's padmux/PUSE checks | [V] |
|
||||
| V3 | Padmux equals the vendor's | DTB diff from the built uImage | [V] |
|
||||
| V4 | Sensor driver register-equivalent to the vendor's | `gc5603-difftest`: 76,011 checks plus fault injection | [V] |
|
||||
| V5 | Rootfs contains the driver, IQ, scripts, tools | Rootfs listing | [V] |
|
||||
| V6 | Pelco-D frames byte-exact | `make test` | [V] |
|
||||
| V7 | `pelco-ptz` end to end on a serial line | `make e2e` (pty head) | [V] |
|
||||
| V8 | ONVIF PTZ end to end | `tests/onvif_e2e.py`: 23/23; unpatched fails 7 | [V] |
|
||||
| V9 | `mcl18d-af` converges, also with late snapshots | `make af` simulation (10.6) | [V] |
|
||||
| V10 | Shell scripts parse before and after stripping | `test_shell_parse.sh`, `test_strip_shell_comments.sh` (STRICT) | [V] |
|
||||
| V11 | CI selector consistent | `ci-matrix.py --self-test` | [V] |
|
||||
| V12 | Lens protocol facts | `af-board-re/verify.py`: 40/40 | [V] (against vendor code) |
|
||||
| V13 | `keepalive` frames whole and on time; commands intact between them | `make e2e` | [V] |
|
||||
| H1 | Boots; sensor detected; video streams | Camera | [V] 2026-10-28 |
|
||||
| H2 | Orientation upright at M0F0 | Camera | [V] |
|
||||
| H3 | Day/night polarity, IR-cut direction, lamps | Camera | In part: majestic follows GPIO 23 and, at night, opens the IR-cut, goes grey and drives GPIO 9 [V]. GPIO 23 never seen at 0, IR LEDs never seen lit [A] |
|
||||
| H4 | GPIO 10/61 boot levels correct | Camera | [A]; GPIO 61's role corrected from vendor code [D] |
|
||||
| H5 | SD card, microphone, speaker polarity, reset button, alarm input | Camera | [A] |
|
||||
| H6 | Lens board obeys zoom/focus/iris at 57600 | Camera + lens board | [V] zoom and focus, with the keep-alive only; iris not checked |
|
||||
| H7 | `/image.jpg?crop=` works; snapshot noise < 0.5% | Camera | crop: no, HTTP 501. Noise: 0.1–0.6% in a still scene [V] |
|
||||
| H8 | `mcl18d-af` finds focus on the real lens | Camera | [V] 12–27 s, 99.4–99.6% of the best snapshot |
|
||||
| H9 | Pan/tilt head at 57600: moves, presets, position replies | Camera + head | [V] moves (shell and ONVIF) and presets work, with the keep-alive; no position replies |
|
||||
|
||||
---
|
||||
|
||||
## 13. Risks and open issues
|
||||
|
||||
| # | Risk / issue | Impact | Mitigation |
|
||||
|---|---|---|---|
|
||||
| R1 | Only part of it has run on hardware (H1, H2, H6–H9, H3 in part) | IR LEDs, GPIO 10/61, SD, audio unchecked | Do H3–H5 next |
|
||||
| R2 | IQ file is GC4023's, as the vendor uses | Colour/noise tuning not specific to GC5603 | Same as the vendor; tune later |
|
||||
| R3 | The board sleeps without AF frames, and wakes into a ~20 s focus sweep | Nothing on D7 works without `pelco-ptz keepalive`; if it dies, PTZ stops | `S94mcl18d` starts it; `ps`/`logread` show `PTZ_KEEPALIVE_START` |
|
||||
| R4 | A pan/tilt head and the lens board share one UART at 57600 | A head that can't do 57600 cannot be used with the lens board | Separate port or an adapter (none on this board) |
|
||||
| R5 | JPEG size as the focus metric | Noise at night or high gain; scene motion | `-n`, `-g`; run in a still scene |
|
||||
| R6 | `pelco-ptz` process start-up inside the focus pulse | Pulse length jitter of a few ms | Approach steps of 150 ms; sweeps time themselves from `/proc/uptime` |
|
||||
| R7 | Not upstreamable as is | Vendor register tables and a factory IQ blob | Keep local; see LEARNING-GUIDE §15 |
|
||||
| R8 | ONVIF password random until set | NVR can't log in | Run `onvif-passwd` with root's password |
|
||||
| R9 | `video0.size` 2560×1440, below the sensor's 2960×1666 output | Lower resolution than the sensor delivers | Matches the vendor: this camera's saved config streams `2560X1440`, and the spec sheet lists 2560×1440 as its 30 fps main stream. Full size is untested. |
|
||||
| R10 | No absolute pan/tilt positions and no position feedback from this head | ONVIF AbsoluteMove/RelativeMove not offered; GetStatus shows the last commanded position | Presets are the head's absolute positions |
|
||||
| R11 | Heat: with the heat sink loose the SoC reached 76 °C | Resets, failed memory self-test, kernel oops on corrupted memory, colour flares every 5–15 s | Heat sink refitted 2026-10-28: 63 °C steady, no resets; flares rarer but not gone (R12) |
|
||||
| R12 | Colour flares: now and then a frame turns to random noise below a random row, mostly within seconds of a large lighting change | Visible glitches in the stream | Cause open. Ruled out: UART traffic, black-level writes, motors, mid-frame writes of frame length, gain index or analog gain page, VIF FIFO errors |
|
||||
| R13 | The light board's day/night output (GPIO 23) and its IR LEDs never seen to change | Night vision unconfirmed | Cover the board's photoresistor in a dark room; check the light board's supply on D5 |
|
||||
| R14 | `set_gpio(12, 0) error` at every majestic start | Speaker enable may not work | Not investigated |
|
||||
|
||||
---
|
||||
|
||||
## 14. Source locations
|
||||
|
||||
| Component | Location |
|
||||
|---|---|
|
||||
| Board files, package, patches | `openipc/firmware` branch `mcl18d-port` (uncommitted) |
|
||||
| Sensor driver source | `openipc/sensors` branch `gc5603-infinity6c` |
|
||||
| Device tree source | `openipc/linux-infinity6c` branch `mcl18d` |
|
||||
| onvif-simple-server fix source | `openipc/onvif_simple_server` branch `ptz-fixes` |
|
||||
| Sensor differential test | `openipc/gc5603-difftest/` |
|
||||
| Lens protocol emulation and checks | `openipc/af-board-re/` |
|
||||
| Built images | `openipc/images/` |
|
||||
| Vendor references | `flash_dump_ssc377d/` (authoritative), `firmware_MCL18D_V3.6.1.3/` (update file; see LEARNING-GUIDE §18 for two files of unknown origin there) |
|
||||
@@ -0,0 +1,267 @@
|
||||
"""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
|
||||
@@ -0,0 +1,72 @@
|
||||
"""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}')
|
||||
@@ -0,0 +1,50 @@
|
||||
"""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}')
|
||||
@@ -0,0 +1,302 @@
|
||||
"""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, '../../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)
|
||||
@@ -0,0 +1,9 @@
|
||||
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
|
||||
Submodule
+1
Submodule firmware added at 7d213e9cd4.
@@ -0,0 +1,192 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,201 @@
|
||||
"""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
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
e1f0f27405ad4c94718ded052aa0fda4 rootfs.squashfs.ssc377d
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
af07489de65c3ab52fe7088fd20bb577 uImage.ssc377d
|
||||
Submodule
+1
Submodule ipctool added at 2a19fe04eb.
Submodule
+1
Submodule linux-infinity6c added at d17f67f1f9.
Submodule
+1
Submodule majestic-af added at 67a96316d2.
Submodule
+1
Submodule onvif_simple_server added at 7c8672fe84.
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# Write patches/<submodule>.patch from each submodule's uncommitted work
|
||||
# (tracked edits plus untracked files) against its pinned upstream commit.
|
||||
# Apply on a fresh checkout with: git -C <submodule> apply ../patches/<submodule>.patch
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
declare -A exclude=(
|
||||
# Seafile collapses this case-colliding pair onto one file; not a real change
|
||||
[linux-infinity6c]=':!tools/memory-model/litmus-tests/Z6.0+pooncelock+pooncelock+pombonce.litmus'
|
||||
)
|
||||
|
||||
for repo in $(git config -f .gitmodules --get-regexp '\.path$' | awk '{print $2}'); do
|
||||
# Scratch index seeded from the real one, so the submodule's own index is untouched
|
||||
idx=$(git -C "$repo" rev-parse --path-format=absolute --git-path index.export)
|
||||
cp "$(git -C "$repo" rev-parse --path-format=absolute --git-path index)" "$idx"
|
||||
GIT_INDEX_FILE=$idx git -C "$repo" add -A
|
||||
GIT_INDEX_FILE=$idx git -C "$repo" diff --cached --binary HEAD -- . ${exclude[$repo]:-} >"patches/$repo.patch"
|
||||
rm -f "$idx"
|
||||
if [[ -s patches/$repo.patch ]]; then
|
||||
echo "$repo: $(grep -c '^diff --git' "patches/$repo.patch") files"
|
||||
else
|
||||
rm "patches/$repo.patch"
|
||||
fi
|
||||
done
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
||||
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>;
|
||||
+ };
|
||||
+ };
|
||||
+};
|
||||
@@ -0,0 +1,105 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,960 @@
|
||||
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 @@
|
||||
+/*
|
||||
+ * 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);
|
||||
Submodule
+1
Submodule sensors added at f9cbec3405.
Reference in new issue
Block a user