From 64e8a30e5b03769f30fe0a2846b300461ab7df71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ryb=C3=A1rsky?= Date: Mon, 23 Nov 2026 22:01:43 +0100 Subject: [PATCH] RTSP image: full-resolution streaming, SSH, recording, installers variants/rtsp.sh assembles the complete firmware: DTB with a 24 MB ION heap for 2304x1296, Tuya-free APP with the SDK runtime, rebuilt RTSP server, dropbear, OTA, Wi-Fi and camcfg tools, DATA partition, patched env, and stages full.bin, partitions and both SD install sets. Co-Authored-By: Claude Opus 5.5 --- BUILD_AND_INSTALL.md | 198 ++++++++++++++++++++++ RTSP.md | 164 ++++++++++++++++++ toolkit/layout-rtsp.conf | 15 ++ toolkit/variants/rtsp.sh | 358 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 735 insertions(+) create mode 100644 BUILD_AND_INSTALL.md create mode 100644 RTSP.md create mode 100644 toolkit/layout-rtsp.conf create mode 100755 toolkit/variants/rtsp.sh diff --git a/BUILD_AND_INSTALL.md b/BUILD_AND_INSTALL.md new file mode 100644 index 0000000..f6e9fc4 --- /dev/null +++ b/BUILD_AND_INSTALL.md @@ -0,0 +1,198 @@ +# Build & Install + +End-to-end: build a firmware image with the toolkit, flash it, repartition, and (for the +RTSP build) add the ONVIF binaries. For background/why, see `README.md`, `RTSP.md`, `OPENIPC.md`. + +> **Always keep `camera_flash.bin` (your original dump).** It's your restore image. + +--- + +## 0. Prerequisites (build host, Linux) + +```sh +sudo apt install squashfs-tools mtd-utils flashrom # mksquashfs, mkfs.jffs2, flashrom +``` +Plus your SPI programmer (e.g. CH341A) wired to the ZB25VQ64 chip, or serial/U-Boot access. + +Everything below runs from the `toolkit/` directory: +```sh +cd toolkit +./fetch-deps.sh && ./build-deps.sh # third-party inputs + our tools (once) +./split.sh ../camera_flash.bin parts/stock # your dump -> partitions +``` + +--- + +## 1. Pick an image and build it + +All three keep stock U-Boot/kernel and give a root shell (telnet :23 + serial). They differ +in what else they do: + +| Image | What it is | Layout | +|---|---|---| +| `camera_flash_telnet.bin` | Tuya intact-ish, adds telnet+wifi+overlay | stock (no repartition) | +| `camera_flash_local.bin` | **Tuya removed** + 2.9M writable DATA | repartitioned | +| `camera_flash_rtsp.bin` | Tuya removed + **RTSP server** (+ONVIF scaffold) + DATA | repartitioned | + +Build (bake in your Wi-Fi so it auto-joins): +```sh +WIFI_SSID='MyNet' WIFI_PSK='MyPass' ./variants/telnet.sh # -> out/camera_flash_telnet.bin +WIFI_SSID='MyNet' WIFI_PSK='MyPass' ./variants/local.sh # -> out/camera_flash_local.bin +WIFI_SSID='MyNet' WIFI_PSK='MyPass' ./variants/rtsp.sh # -> out/camera_flash_rtsp.bin +``` +`WIFI_SSID` is required (`WIFI_SSID=` = no built-in network). On the rtsp image you change +Wi-Fi later with `wifi-set`/`camcfg wifi`, or a `wifi.txt` on the SD card (GUIDE.md §7). + +Rebuild the stock image unchanged (sanity check — reproduces your dump byte-for-byte): +```sh +./build-image.sh parts/stock out/stock_rebuilt.bin +``` + +--- + +## 2. Flash + +### A. SPI programmer (recommended) +Chip powered by the programmer, board off, clip on the ZB25VQ64: +```sh +flashrom -p ch341a_spi -w out/camera_flash_rtsp.bin # pick your image +# restore anytime: +flashrom -p ch341a_spi -w ../camera_flash.bin +``` +(Adjust `-p` for your programmer. The whole chip is written; only the changed partitions differ.) + +### B. SD card + U-Boot (no programmer, recommended if no programmer) +Your U-Boot has `mmc`/`fatload`/`sf`, so it can read the image off a FAT SD card and write it +to SPI-NOR. Flash **only the changed partitions** (APP + DATA) — this never touches +U-Boot/env/kernel/rootfs, so it can't brick the bootloader. + +1. **Prepare the card:** format a (micro)SD as **FAT32**, and copy the staged files from + `sdcard/` to its root: + ``` + app.bin (the new APP squashfs) + data.bin (the empty writable DATA) + ``` +2. **At the `=>` prompt** (Ctrl+C at power-on), insert the card and run: + ``` + mmc dev 0 + fatls mmc 0 # confirm app.bin / data.bin are listed + sf probe + + fatload mmc 0 ${loadaddr} app.bin + sf erase 0x300000 0x2e0000 + sf write ${loadaddr} 0x300000 ${filesize} + + fatload mmc 0 ${loadaddr} data.bin + sf erase 0x5e0000 0x220000 + sf write ${loadaddr} 0x5e0000 ${filesize} + ``` + Then do the repartition in step 3 (`setenv mtdparts … ; saveenv ; reset`). + - `${loadaddr}` is `0x80008000` (already in env). `${filesize}` is set by each `fatload` + (you should see `2822144` then `2228224` — matching the table above). + - `mmc dev` takes only the device number — `mmc dev 0`, **not** `mmc dev 0 1` (the second + arg is an eMMC hw-partition that SD doesn't have, and errors). + - A FAT-formatted SD is usually a "superfloppy" (no MBR), so address it as **`mmc 0`** + with no `:part`. If yours has a partition table, use `mmc 0:1`. + - For the **telnet** image (stock layout) the single changed partition is APP at + `0x300000`, slot `0x500000` — `sf erase 0x300000 0x500000` then write `app.bin`; no repartition. + +**Full-chip from SD (optional, riskier):** `fatload mmc 0:1 ${loadaddr} full.bin; sf probe; sf erase 0 0x800000; sf write ${loadaddr} 0 0x800000` — this also rewrites U-Boot/env, so a bad write/power loss can brick it. Prefer the partition method above. + +### C. Serial / U-Boot — write a partition via Y-modem (no SD, no programmer) +At the `=>` prompt (≈8 min for a ~2.7 MB APP at 115200). Send the part file from your terminal: +``` +loady 0x80008000 # then send toolkit/parts/rtsp/app.bin (Y-modem) +sf probe +sf erase 0x300000 0x2e0000 +sf write 0x80008000 0x300000 ${filesize} +reset +``` +Repeat for `data.bin` at its offset. (U-Boot TFTP needs an Ethernet PHY — this is a Wi-Fi +model, so use SD, Y-modem, or the programmer.) + +--- + +## 3. One-time repartition (only for `local` / `rtsp` images) + +The DTB has no partition table — the kernel gets partitions from the U-Boot `mtdparts` env. +After flashing a repartitioned image, break to `=>` and run **once**, then `reset`: + +**local image:** +``` +setenv mtdparts 'mtdparts=spi-nor:200k@0x0(UBOOT),4k@0x32000(ENV),4k@0x33000(ENVBK),64k@0x34000(DTB),1536k@0x44000(KERNEL),1008k@0x1c4000(ROOTFS),256k@0x2c0000(CONFIG),2176k@0x300000(APP),2944k@0x520000(DATA)' +saveenv +reset +``` +**rtsp image:** +``` +setenv mtdparts 'mtdparts=spi-nor:200k@0x0(UBOOT),4k@0x32000(ENV),4k@0x33000(ENVBK),64k@0x34000(DTB),1536k@0x44000(KERNEL),1008k@0x1c4000(ROOTFS),256k@0x2c0000(CONFIG),2944k@0x300000(APP),2176k@0x5e0000(DATA)' +saveenv +reset +``` +`boot_normal` rebuilds `bootargs` from `${mtdparts}` every boot, so that's all it takes. +DATA then appears as `mtd8` (`/dev/mtdblock8`). Reversible: `setenv` it back, or restore the dump. +(The `telnet` image uses the stock layout — skip this step.) + +--- + +## 4. First boot / get in + +- The camera joins your Wi-Fi and starts **telnet** (passwordless root) on port 23, plus a + root shell on the serial console. +```sh +telnet +cat /tmp/local_bootstrap.log # wifi/overlay/service startup +``` +- Make any file editable+persistent: `rw /path/to/file` (backed by DATA/overlay). +- ⚠️ No watchdog is petted (Tuya service removed). If the board resets ~1 min into boot, add + `[ -e /dev/watchdog ] && watchdog -t 5 /dev/watchdog` early in `local_bootstrap.sh` and rebuild. + +--- + +## 5. RTSP (rtsp image only) + +Starts automatically. H.264, port 554: +``` +rtsp:///vs0 # main 1920x1080 +rtsp:///vs1 # sub 640x360 +``` +View: `ffplay rtsp:///vs0`. Check `cat /tmp/rtsp.log` if no stream. +**Status: assembled from the public Anyka SDK, ABI-matched, not yet hardware-tested** — see +`RTSP.md` for validation (venc/lib version match, ISP config). + +--- + +## 6. ONVIF (rtsp image only) — build + install the two binaries + +Config + web/discovery wiring + autostart are already baked in; you supply the binaries. + +**Build** (static, so libc doesn't matter): +```sh +git clone https://github.com/roleoroleo/onvif_simple_server && cd onvif_simple_server +export CC=-gcc # OpenIPC arm-openipc-linux-musleabi-gcc, or the Anyka toolchain +make -f Makefile.static CC=$CC HAVE_MBEDTLS=y \ + INCLUDE="-I/include" LIBS_O="-L/lib -lmbedcrypto -ljson-c -lz -lpthread -lrt" +# outputs: onvif_simple_server wsd_simple_server onvif_notify_server +``` +(Or lift prebuilt ARM `onvif_simple_server`/`wsd_simple_server` from an OpenIPC/thingino rootfs.) + +**Install** on the camera (over telnet): +```sh +mkdir -p /data/onvif/wsd_files +# copy from your build host into /data/onvif/ : +# onvif_simple_server wsd_simple_server wsd_files/* (+ any *_service_files) +chmod +x /data/onvif/onvif_simple_server /data/onvif/wsd_simple_server +sh /usr/local/onvif/start_onvif.sh # or reboot — it auto-starts when binaries exist +``` +ONVIF is then discoverable at `http://:8080/cgi-bin/device_service`; add it in +Frigate / Home Assistant / ONVIF Device Manager. Details and gotchas: `RTSP.md`. + +--- + +## 7. Recovery + +```sh +flashrom -p ch341a_spi -w ../camera_flash.bin +``` +As long as UBOOT/ENV are intact you also have the `=>` prompt on serial to re-flash via +Y-modem (step 2B). This is why the images never touch UBOOT/ENV/DTB/kernel. diff --git a/RTSP.md b/RTSP.md new file mode 100644 index 0000000..00794d5 --- /dev/null +++ b/RTSP.md @@ -0,0 +1,164 @@ +# Local RTSP (+ ONVIF) on the AK3918AV130 — using the public Anyka SDK + +## Short answer to "are the OpenIPC parts useful?" + +**Yes — they point straight to the solution.** OpenIPC's `anyka-osdrv-ak3918av130` +package doesn't bundle the closed userspace libs itself; it pulls them from a **public** +Anyka SDK: **`github.com/Link-WQS/ANYKA_130L_SDK`**, built for kernel **4.4.302-cip94 — +your exact kernel**. That SDK ships everything needed for a local stream: + +- `platform/sample/rtsp/` — a ready RTSP sample, including a **prebuilt `ak_rtsp_server_sample`** (36 KB) +- `librtsp_server.so` — an RTSP server library +- `libmpi_venc` (H.264), `libplat_vi`, `libplat_isp_sdk`, `libapp_video`, `libapp_ats/its`, audio libs — the full media pipeline +- the prebuilt binary is **ARM EABI5, dynamically linked to `/lib/ld-uClibc.so.0`** — the *exact* dynamic linker in your stock rootfs, so it runs without recompiling. + +So the "private SDK" worry was wrong for the userspace stack. My earlier "needs a private +build" was incorrect — this is assemblable from public parts. + +## What `camera_flash_rtsp.bin` contains + +Built by `toolkit/variants/rtsp.sh` from the staged SDK blobs in `toolkit/blobs/anyka-rtsp/`: + +- stock UBOOT/ENV/DTB/**kernel 4.4.302-cip94**/ROOTFS/CONFIG (unchanged) +- **APP (2944 K)** = Tuya-stripped userland **+ 23 SDK `.so` libs + `ak_rtsp_server_sample` + `rtsp.ini`** +- **DATA (2176 K)** = writable jffs2 (overlay + your files) +- boot: loads the video modules (already in stock `main.sh`: `ak_isp`, `sensor_sc3332`, + `ak_venc_adapter/bridge`, `ak_pcm`, `ak_uio`), joins Wi-Fi, starts telnet + serial shell, + then launches the RTSP server. + +**Streams** (H.264, port **554**): +- `rtsp:///vs0` — main, 1920×1080 @20, ~2048 kbps +- `rtsp:///vs1` — sub, 640×360 @20, ~400 kbps + +(stream params + the ISP tuning path live in `/usr/local/rtsp.ini`, which is repointed to +your stock `/usr/local/isp_sc3332.conf`.) + +## Status: booted on hardware; RTSP libs load (`libmpi_venc V3.0.02`), stream pending validation + +First on-device boot confirmed the big unknowns: the repartition took (9 MTD partitions, +DATA at 0x5e0000), the SDK userspace libs are **ABI-compatible and load/run** +(`libmpi_venc V3.0.02` prints), and the SC3332 sensor probes. Two bring-up bugs were found +and fixed in the build: + +1. **Wi-Fi driver needs the USB host stack first.** `ATBM6x6x_wifi_usb.ko` depends on + `usbcore` (+`cfg80211`); load order is `usb-common → usbcore → ak_hcd → cfg80211 → + ATBM6x6x_wifi_usb`. Without it: `unknown symbol in module` and no `wlan0`. +2. **The RTSP binary hard-reads `/etc/config/rtsp.ini`** (ignores its argv), so the config + is now copied there at boot. + +Both are in `variants/rtsp.sh`. Still to confirm on your unit: that the encoder opens the +sensor and a client can actually pull the stream (see below). + +## Flash + bring-up + +1. **Flash** (keep `camera_flash.bin` as your restore image): + ```sh + flashrom -p ch341a_spi -w toolkit/out/camera_flash_rtsp.bin + ``` +2. **One-time repartition** at the U-Boot `=>` prompt (adds the DATA partition; `boot_normal` + rebuilds `bootargs` from `${mtdparts}`), then `reset`: + ``` + setenv mtdparts 'mtdparts=spi-nor:200k@0x0(UBOOT),4k@0x32000(ENV),4k@0x33000(ENVBK),64k@0x34000(DTB),1536k@0x44000(KERNEL),1008k@0x1c4000(ROOTFS),256k@0x2c0000(CONFIG),2944k@0x300000(APP),2176k@0x5e0000(DATA)' + saveenv + reset + ``` +3. **Connect** (telnet, once Wi-Fi is up) and watch the RTSP log: + ```sh + telnet + cat /tmp/rtsp.log # encoder/RTSP init messages + cat /tmp/local_bootstrap.log + ``` +4. **View**: `ffplay rtsp:///vs0` (or VLC → Open Network Stream). + +## Validation / troubleshooting (do these first) + +- **venc ↔ lib version match (the main risk).** The kernel modules are your stock ones + (SDK ~V1.01); the userspace libs are from Link-WQS SDK. If `/tmp/rtsp.log` shows venc/isp + ioctl errors, swap the kernel modules for the OpenIPC `anyka-osdrv-ak3918av130/files/kmod` + set (same SDK lineage, built for 4.4.302-cip94): drop them into `toolkit/src/app/modules/` + and rebuild, or `insmod` the matching ones over telnet to test. +- **ISP config.** If the sensor won't open, the SDK may expect its own + `isp_sc3332_mipi_2lane_av130.conf` format. Pull it from the SDK's rootfs and point + `rtsp.ini`'s `isp_conf` at it (edit `/usr/local/rtsp.ini` via `rw /usr/local/rtsp.ini`). +- **How it finds the config.** The server is launched as `cd /usr/local && ak_rtsp_server_sample rtsp.ini`. + If it ignores the arg, it reads `./rtsp.ini` from that cwd (why we `cd` there first). +- **No watchdog is petted** (Tuya service is gone). If the board resets ~1 min into boot, + add `[ -e /dev/watchdog ] && watchdog -t 5 /dev/watchdog` early in `local_bootstrap.sh`. +- Everything in APP is read-only squashfs; use `rw /path` to edit a file persistently, or + put test copies on `/data` and adjust `LD_LIBRARY_PATH`. + +## Rebuild with your own Wi-Fi / tweaks + +```sh +cd toolkit +WIFI_SSID='MyNet' WIFI_PSK='MyPass' ./variants/rtsp.sh +``` +Edit `toolkit/blobs/anyka-rtsp/rtsp.ini` (resolution/bitrate) or swap libs/binary there and +rebuild. The 23 SDK libs + binary live in `toolkit/blobs/anyka-rtsp/` (fetched from the +public SDK); re-fetch newer ones from `Link-WQS/ANYKA_130L_SDK/platform/{lib,sample/rtsp}`. + +## ONVIF (Profile S) — config + wiring are baked in; build + drop in the binaries + +ONVIF is the discovery/metadata layer NVRs and apps use to auto-find the camera and learn +its RTSP URL. There's no prebuilt uClibc ONVIF binary, so you build the (small, open source) +`onvif_simple_server` — but **everything around it is already set up** in the image: + +- **Config** `/usr/local/onvif/onvif.conf` — tailored to this camera: two Profile S + profiles pointing at `rtsp://%s/vs0` (1080p) and `rtsp://%s/vs1` (360p), H264, port 8080, + no auth, PTZ/events off. (`%s` = device IP, filled at runtime.) +- **Launcher** `/usr/local/onvif/start_onvif.sh` — copies the config to + `/etc/onvif_simple_server.conf`, creates the per-service CGI symlinks + (`device_service`, `media_service`, …; the binary picks its service from `argv[0]`), + starts **busybox httpd** on :8080 serving `/cgi-bin/`, and starts **`wsd_simple_server`** + (WS-Discovery) advertising `http://:8080/cgi-bin/device_service`. +- **Auto-start** — `local_bootstrap.sh` already runs the launcher on boot **as soon as the + binaries exist** at `/data/onvif/` (so nothing happens until you drop them in). + +### Build the binaries + +```sh +git clone https://github.com/roleoroleo/onvif_simple_server && cd onvif_simple_server +# Use an ARM cross toolchain. Build STATIC so the libc (musl/uClibc) doesn't matter — +# a static ARM binary runs fine on this kernel regardless of the rootfs libc. +export CC=-gcc # e.g. the OpenIPC arm-openipc-linux-musleabi-gcc +# needs json-c + zlib + a crypto lib (mbedtls/libtomcrypt/wolfssl) cross-built for ARM; +# with no auth configured, WS-Security isn't exercised but the lib is still linked. +make -f Makefile.static CC=$CC HAVE_MBEDTLS=y \ + INCLUDE="-I/include" LIBS_O="-L/lib -lmbedcrypto -ljson-c -lz -lpthread -lrt" +# outputs: onvif_simple_server wsd_simple_server onvif_notify_server +``` +(If cross-building the deps is a hassle, grab prebuilt ARM `onvif_simple_server`/`wsd_simple_server` +from an OpenIPC or thingino rootfs — they ship these built for ARMv5.) + +### Drop them into the camera (over telnet) + +```sh +mkdir -p /data/onvif/wsd_files +# scp/tftp from your build host into /data/onvif/ : +# onvif_simple_server wsd_simple_server +# wsd_files/* (WS-Discovery templates from the repo) +# any *_service_files the build expects (keep the repo's layout) +chmod +x /data/onvif/onvif_simple_server /data/onvif/wsd_simple_server +sh /usr/local/onvif/start_onvif.sh # or just reboot — it auto-starts +``` + +### Test + +- Discovery: **ONVIF Device Manager**, `onvif-cli`, or add it in **Frigate / Home Assistant / Blue Iris** — it should appear and expose `/vs0` and `/vs1`. +- Manual: `curl -s http://:8080/cgi-bin/device_service -d @GetSystemDateAndTime.xml` + +### Notes / gotchas + +- busybox runs anything under `/cgi-bin/` as CGI, so no busybox patch is needed with the + `/cgi-bin/` URLs used here. If an ONVIF client instead expects `/onvif/` + URLs, either rebuild busybox with OpenIPC's `0102-add-onvif-dir-support.patch` or front it + with lighttpd mapping `/onvif/*` → the CGI, and update the `-x` XAddr in `start_onvif.sh`. +- Edit identity/profiles in `toolkit/blobs/onvif/onvif.conf` and rebuild, or live-edit on the + device with `rw /usr/local/onvif/onvif.conf`. + +## If this path stalls + +The alternative is full **OpenIPC** (Majestic = RTSP, its onvif packaged), which replaces +the stock uClibc rootfs with OpenIPC's musl rootfs — see `OPENIPC.md`. The RTSP stack here +is the lighter route because it keeps your stock kernel + rootfs and just adds the SDK's own +server. diff --git a/toolkit/layout-rtsp.conf b/toolkit/layout-rtsp.conf new file mode 100644 index 0000000..d4b6505 --- /dev/null +++ b/toolkit/layout-rtsp.conf @@ -0,0 +1,15 @@ +# Anyka AK3918AV130 — 8 MiB SPI-NOR, RTSP variant (Tuya-free + Anyka SDK RTSP) +# APP holds the stripped rootfs + the public Anyka SDK RTSP runtime (libs+binary). +# One-time U-Boot mtdparts change required: +# setenv mtdparts 'mtdparts=spi-nor:200k@0x0(UBOOT),4k@0x32000(ENV),4k@0x33000(ENVBK),64k@0x34000(DTB),1536k@0x44000(KERNEL),1008k@0x1c4000(ROOTFS),256k@0x2c0000(CONFIG),2944k@0x300000(APP),2176k@0x5e0000(DATA)' +# saveenv +# name offset size kind file +UBOOT 0x000000 0x032000 raw uboot.bin +ENV 0x032000 0x001000 raw env.bin +ENVBK 0x033000 0x001000 raw envbk.bin +DTB 0x034000 0x010000 raw dtb.bin +KERNEL 0x044000 0x180000 raw kernel.bin +ROOTFS 0x1c4000 0x0fc000 fs rootfs.bin +CONFIG 0x2c0000 0x040000 fs config.bin +APP 0x300000 0x2e0000 fs app.bin +DATA 0x5e0000 0x220000 fs data.bin diff --git a/toolkit/variants/rtsp.sh b/toolkit/variants/rtsp.sh new file mode 100755 index 0000000..0e82d07 --- /dev/null +++ b/toolkit/variants/rtsp.sh @@ -0,0 +1,358 @@ +#!/bin/sh +# Build the Tuya-free RTSP image using the PUBLIC Anyka SDK runtime +# (Link-WQS/ANYKA_130L_SDK, staged in toolkit/blobs/anyka-rtsp). See IMAGE_CONTENTS.md. +# - DTB: ION video heap 18M -> 24M (needed for 2304x1296) +# - APP: Tuya stack removed; SDK libs + RTSP server (rebuilt with Digest auth), +# matching venc modules, dropbear SSH, fwupdate/mtdflash OTA, wifi-set +# - DATA: new 2176K writable jffs2 (settings, SSH keys, overlay) +# - ENV/ENVBK: your env + mtdparts/bootcmd/sdscript for this layout (full image only) +# - UBOOT/KERNEL/ROOTFS/CONFIG: copied unchanged from parts/stock (= YOUR dump) +# - everything staged in ../sdcard (STAGE_DIR=): full.bin app.bin dtb.bin data.bin env.bin +# Requires the one-time U-Boot mtdparts change in layout-rtsp.conf. +# Build-time settings (env): WIFI_SSID WIFI_PSK ROOT_PW RTSP_USER RTSP_PASS +# MAIN_W MAIN_H MAIN_FPS MAIN_KBPS MAIN_CODEC ION_MB PREBUILT_RTSP +set -e +HERE="$(cd "$(dirname "$0")/.." && pwd)" +BLOB="$HERE/blobs/anyka-rtsp" +# must be given explicitly; WIFI_SSID= (empty) = no default network (use SD wifi.txt / wifi-set) +[ "${WIFI_SSID+set}" = set ] || { echo "set WIFI_SSID=... WIFI_PSK=... (or WIFI_SSID= to configure Wi-Fi from the SD card)"; exit 1; } +WIFI_PSK=${WIFI_PSK-} +[ -n "$ROOT_PW" ] || echo "[rtsp.sh] WARNING: ROOT_PW not set - using the public default password 'anyka' (SSH + RTSP)" +ROOT_PW=${ROOT_PW:-anyka} +SET="$HERE/parts/rtsp"; LAYOUT="$HERE/layout-rtsp.conf" +WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT +mkdir -p "$SET" +[ -d "$BLOB/lib" ] && [ -x "$HERE/blobs/fwupdate/mtdflash" ] || { echo "missing dependencies: run ./fetch-deps.sh && ./build-deps.sh"; exit 1; } + +for f in uboot env envbk dtb kernel rootfs config; do cp -a "$HERE/parts/stock/$f.bin" "$SET/"; done +# U-Boot env for the FULL image: this layout's mtdparts + the SD-update bootcmd, so +# camera_flash_rtsp.bin works standalone (e.g. via a programmer) with no U-Boot typing. +# (Partition flashing never writes ENV; there you set these once by hand - GUIDE.md §5.) +MTDPARTS=$(grep -vE '^\s*#|^\s*$' "$LAYOUT" | while read name off size kind file; do + printf '%dk@0x%x(%s),' $((size / 1024)) $((off)) "$name"; done) +MTDPARTS="mtdparts=spi-nor:${MTDPARTS%,}" +BOOTCMD='mmc dev 0; mw.b ${loadaddr} 0 0x1000; fatload mmc 0 ${loadaddr} camupdate.env; env import -t ${loadaddr} 0x1000; run sdscript; setenv sdscript version; run boot_normal' +# build id = the vendor SD-recovery version (ht_fw_version): a camera whose env holds this +# value ignores a leftover ht_recover_fw.conf with the same id (no re-flash loops) +FWVER=${FWVER:-cr$(date +%y%m%d%H%M%S)} +for e in env envbk; do + python3 "$HERE/env-patch.py" "$SET/$e.bin" "$SET/$e.bin" "mtdparts=$MTDPARTS" "bootcmd=$BOOTCMD" \ + "sdscript=version" "ht_fw_version=$FWVER" +done +echo "[rtsp.sh] env: $MTDPARTS" +# enlarge the ION video-memory heap (stock 18M): the SDK sample doesn't share VI/venc +# buffers like the Tuya app did, so 2304x1296 needs more. Same blob size (U-Boot reads a +# fixed dtb_size=0xe351), re-padded to the 64K slot. ION_MB=18 keeps stock. +ION=$(printf '0x%x' $(( ${ION_MB:-24} * 1024 * 1024 ))) +TS=$(fdtdump "$SET/dtb.bin" 2>/dev/null | grep -m1 totalsize | grep -oE '0x[0-9a-f]+') +head -c $((TS)) "$SET/dtb.bin" > "$WORK/dtb.raw" +fdtput -t x "$WORK/dtb.raw" /reserved-memory/dma_reserved@0x81400000 size "$ION" +fdtput -t x "$WORK/dtb.raw" /reserved-memory/dma_reserved@0x81400000 reg 0x81400000 "$ION" +fdtput -t x "$WORK/dtb.raw" /ion/dma_reserved_heap size "$ION" +[ "$(stat -c %s "$WORK/dtb.raw")" -eq $((TS)) ] || { echo "dtb size changed"; exit 1; } +{ cat "$WORK/dtb.raw"; head -c $((0x10000 - TS)) /dev/zero | tr '\0' '\377'; } > "$SET/dtb.bin" +echo "[rtsp.sh] ION heap set to $ION" + +# ---- app tree: stripped + RTSP runtime ---- +"$HERE/extract-src.sh" +cp -a "$HERE/src/app" "$WORK/app"; cd "$WORK/app" +find . -depth -name '*.extracted' -type d -exec rm -rf {} + 2>/dev/null || true +rm -f bin/anyka_ipc bin/msgserver bin/cmdserver bin/system_upgrade +rm -f local/model_0x0A000000_V1.1.0.bin local/ak_font_16.bin share/*.mp3 +cp "$BLOB"/lib/*.so lib/ # -> /usr/lib +# rebuilt-from-source sample with RTSP Digest auth (src/rtsp_sample); PREBUILT_RTSP=1 = stock sample, no auth +if [ "${PREBUILT_RTSP:-0}" = 1 ] || [ ! -f "$BLOB"/bin/ak_rtsp_server_sample.auth ]; then + cp "$BLOB"/bin/ak_rtsp_server_sample bin/ +else + cp "$BLOB"/bin/ak_rtsp_server_sample.auth bin/ak_rtsp_server_sample +fi +chmod 0755 bin/ak_rtsp_server_sample +cp "$BLOB"/rtsp.ini local/rtsp.ini +# point the ISP tuning at the stock SC3332 conf shipped in /usr/local +sed -i 's#^isp_conf *=.*#isp_conf = /usr/local/isp_sc3332.conf#' local/rtsp.ini +# main stream at the SC3332's native 2304x1296 ("2K"/3MP). fps 15 = cap in the stock ISP conf +# (sensor max is 25, but isp_sc3332.conf frame_rate=15). Was 1080p@20, 2 Mbps; stock Tuya: 1.5 Mbps. +# 8 Mbps H.264 default; MAIN_CODEC=h.265 (HW-supported) gives similar quality at ~60% of the bitrate. +# override at build: MAIN_W/MAIN_H/MAIN_FPS/MAIN_KBPS/MAIN_CODEC (h.264|h.265) +awk -v w="${MAIN_W:-2304}" -v h="${MAIN_H:-1296}" -v f="${MAIN_FPS:-15}" -v k="${MAIN_KBPS:-8000}" -v c="${MAIN_CODEC:-h.264}" ' + /^\[/ { sec=$0 } + sec=="[video0]" && /^code_type/ { $0="code_type = " c } + sec=="[video0]" && /^width/ { $0="width = " w } + sec=="[video0]" && /^height/ { $0="height = " h } + sec=="[video0]" && /^fps/ { $0="fps = " f } + sec=="[video0]" && /^target_kbps/ { $0="target_kbps = " k } + sec=="[video0]" && /^target_kbps/ { print; $0="enc_level = " (h > 1080 ? 50 : 40) } + sec=="[video1]" && /^fps/ { $0="fps = " f } + { print }' local/rtsp.ini > local/rtsp.ini.new && mv local/rtsp.ini.new local/rtsp.ini +# RTSP login (Digest). Default admin / same password as root. RTSP_USER= (empty) disables auth. +RTSP_USER=${RTSP_USER-admin}; RTSP_PASS=${RTSP_PASS:-$ROOT_PW} +printf '\n[server]\nport = 554\n\n[auth]\n# empty user = no authentication\nuser = %s\npassword = %s\n' \ + "$RTSP_USER" "$RTSP_PASS" >> local/rtsp.ini +echo "[rtsp.sh] RTSP auth user: ${RTSP_USER:-}" +# SD recording (ak_record.c). Split of the card between the two loops is configurable: +# *_percent = share of the filesystem the folder is on; *_max_mb > 0 overrides it. +# Two SD partitions: point motion_path at /mnt/sd2/... (2nd partition is auto-mounted). +cat >> local/rtsp.ini < "open venc failed") +cp "$BLOB"/modules/ak_venc_adapter.ko "$BLOB"/modules/ak_venc_bridge.ko modules/ +# SSH: static dropbear (-> /usr/sbin) + applet symlinks; replaces telnet +cp "$HERE/blobs/ssh/dropbearmulti" sbin/; chmod 0755 sbin/dropbearmulti +ln -sf dropbearmulti sbin/dropbear +ln -sf dropbearmulti sbin/dropbearkey +ln -sf dropbearmulti sbin/scp +# OTA flashing from Linux: static verified MTD writer + wrapper (see ota.sh) +cp "$HERE/blobs/fwupdate/mtdflash" "$HERE/blobs/fwupdate/fwupdate" sbin/; chmod 0755 sbin/mtdflash sbin/fwupdate +# Wi-Fi: runtime-changeable (wifi-set / SD wifi.txt) with fallback to the build-time default +cp "$HERE"/blobs/wifi/wifi-set "$HERE"/blobs/wifi/wifi-mkconf "$HERE"/blobs/wifi/wifi-connect sbin/ +chmod 0755 sbin/wifi-set sbin/wifi-mkconf sbin/wifi-connect +# camcfg: one CLI for every setting; stores only overrides in /data/camcfg.conf +cp "$HERE"/blobs/camcfg/camcfg sbin/; chmod 0755 sbin/camcfg +rm -f local/wpa_default.conf +if [ -n "$WIFI_SSID" ]; then + sh "$HERE"/blobs/wifi/wifi-mkconf "$WIFI_SSID" "$WIFI_PSK" > local/wpa_default.conf + echo "[rtsp.sh] default Wi-Fi: $WIFI_SSID" +else + echo "[rtsp.sh] no default Wi-Fi baked: configure via SD card wifi.txt" +fi +# timezone (POSIX TZ string, e.g. CET-1CEST,M3.5.0,M10.5.0/3); /data/timezone overrides +echo "${TIMEZONE:-UTC0}" > local/timezone +# default root password -> hashed, applied to /etc/config/shadow at first boot +openssl passwd -1 "$ROOT_PW" | tr -d '\n' > local/root.hash +echo "[rtsp.sh] root SSH password set to: $ROOT_PW (change on device with: passwd)" +# first boot after the DIRECT SD install (U-Boot ht_recover_fw.conf type 100 writes APP+DATA +# only): write this layout's env + the DTB from Linux, then reboot. Runs only while /proc/mtd +# has no DATA partition (stock layout), so never on cameras installed any other way. +mkdir -p local/firstboot +cp "$SET/env.bin" "$SET/envbk.bin" local/firstboot/ +head -c $((TS)) "$SET/dtb.bin" > local/firstboot/dtb.bin +echo "$FWVER" > local/firstboot/version +# ONVIF scaffolding (config + launcher); binaries get dropped into /data/onvif later +mkdir -p local/onvif; cp "$HERE/blobs/onvif/onvif.conf" "$HERE/blobs/onvif/start_onvif.sh" local/onvif/ +chmod 0755 local/onvif/start_onvif.sh +# ONVIF advertises the real main-stream size and uses the same login as RTSP +awk -v w="${MAIN_W:-2304}" -v h="${MAIN_H:-1296}" -v u="$RTSP_USER" -v pw="$RTSP_PASS" ' + /^(snapurl|user|password)=/ { next } # no snapshot CGI shipped + /^width=/ && !wd { $0 = "width=" w; wd = 1 } # first profile = main stream + /^height=/ && !hd { $0 = "height=" h; hd = 1 } + { print } + /^port=/ && u != "" { print "user=" u; print "password=" pw }' \ + local/onvif/onvif.conf > local/onvif/onvif.conf.new && mv local/onvif/onvif.conf.new local/onvif/onvif.conf + +# ---- bootstrap: modules are already insmod'd by main.sh; we add net + rtsp ---- +cat > sbin/local_bootstrap.sh <<'EOS' +#!/bin/sh +PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin +export LD_LIBRARY_PATH=/usr/lib:/lib:/data/lib +exec >/tmp/local_bootstrap.log 2>&1 +echo "[local] start $(date)" + +# writable DATA (mtd8) + overlay +OVROOT=/etc/config/overlay +if [ -e /dev/mtdblock8 ]; then + mkdir -p /data + mount -t jffs2 /dev/mtdblock8 /data 2>/dev/null && OVROOT=/data/overlay +fi +echo "$OVROOT" > /tmp/ovroot; mkdir -p "$OVROOT" + +# --- first boot after the DIRECT SD install: stock env/DTB still in place --- +if [ -d /usr/local/firstboot ] && ! grep -q '"DATA"' /proc/mtd; then + echo "[local] direct SD install: backing up remaining original partitions, writing DTB + env" + mkdir -p /mnt/sd + mount -t vfat /dev/mmcblk0p1 /mnt/sd 2>/dev/null || mount -t vfat /dev/mmcblk0 /mnt/sd 2>/dev/null + if grep -q ' /mnt/sd ' /proc/mounts; then + B=/mnt/sd/original-backup; mkdir -p $B + sed -n 's/^mtd\([0-9]*\): .*"\(.*\)"$/\1 \2/p' /proc/mtd | while read n name; do + [ "$name" = APP ] && continue # already overwritten by U-Boot + [ -f "$B/$name.bin" ] || cat /dev/mtd$n > "$B/$name.bin" + done + echo "Partial backup (direct SD install): everything except APP, which U-Boot had already replaced." > $B/README.txt + ( cd $B && md5sum *.bin > MD5SUMS ); sync + fi + cp /usr/sbin/mtdflash /tmp/mtdflash + /tmp/mtdflash -f -r DTB /usr/local/firstboot/dtb.bin ENVBK /usr/local/firstboot/envbk.bin \ + ENV /usr/local/firstboot/env.bin + echo "[local] firstboot flash FAILED - running on the old layout this boot" +fi + +(setsid /bin/sh /dev/ttySAK0 2>&1) & # serial root shell + +# --- SD card (mmc/exfat modules already loaded by main.sh) -> /mnt/sd --- +mkdir -p /mnt/sd +for d in /dev/mmcblk0p1 /dev/mmcblk0; do + mount -t vfat $d /mnt/sd 2>/dev/null || mount -t exfat $d /mnt/sd 2>/dev/null && break +done +# optional 2nd partition (e.g. a dedicated motion-clip partition) -> /mnt/sd2 +if [ -b /dev/mmcblk0p2 ]; then + mkdir -p /mnt/sd2 + mount -t vfat /dev/mmcblk0p2 /mnt/sd2 2>/dev/null || mount -t exfat /dev/mmcblk0p2 /mnt/sd2 2>/dev/null +fi +if [ -f /mnt/sd/camupdate.env ]; then # U-Boot already flashed it this boot + mv /mnt/sd/camupdate.env /mnt/sd/camupdate.done + echo "[local] SD update was applied by U-Boot -> renamed camupdate.done" +fi +if [ -f /mnt/sd/wifi.txt ]; then # SSID=... / PASSWORD=... lines + S=$(tr -d '\r' < /mnt/sd/wifi.txt | sed -n 's/^SSID=//p' | head -1) + P=$(tr -d '\r' < /mnt/sd/wifi.txt | sed -n 's/^PASSWORD=//p' | head -1) + if [ -n "$S" ] && /usr/sbin/wifi-set "$S" "$P"; then + echo "applied on $(date) for SSID: $S (password removed from card)" > /mnt/sd/wifi.txt.applied + rm -f /mnt/sd/wifi.txt + else + echo "[local] /mnt/sd/wifi.txt invalid (need SSID= and PASSWORD= 8-63 chars)" + fi +fi +sync + +# --- Wi-Fi station: ATBM6x6x is USB -> USB host stack + cfg80211 first --- +for m in usb-common usbcore ak_hcd cfg80211; do insmod /usr/modules/$m.ko 2>/dev/null; done +/usr/sbin/wifi_driver.sh sta; sleep 3 +/usr/sbin/wifi-connect + +# --- clock: NTP (recordings are named by date/time) + timezone --- +TZ=$(cat /data/timezone 2>/dev/null || cat /usr/local/timezone 2>/dev/null || echo UTC0); export TZ +NTP=$(cat /data/ntp_server 2>/dev/null || echo pool.ntp.org) +ntpd -p "$NTP" 2>/dev/null +( sleep 60; hwclock -w 2>/dev/null ) & # keep the RTC roughly right + +# root password: create /etc/config/shadow (persists on CONFIG jffs2) on first boot; +# change it anytime with `passwd` (writes back to the same jffs2 file) +if [ ! -f /etc/config/shadow ] && [ -f /usr/local/root.hash ]; then + echo "root:$(cat /usr/local/root.hash):19000:0:99999:7:::" > /etc/config/shadow + chmod 600 /etc/config/shadow +fi +# SSH (dropbear) instead of telnet; host keys persist on DATA. Serial shell stays as recovery. +mkdir -p /data/dropbear +[ -f /data/dropbear/rsa_host_key ] || dropbearkey -t rsa -f /data/dropbear/rsa_host_key >/dev/null 2>&1 +[ -f /data/dropbear/ed25519_host_key ] || dropbearkey -t ed25519 -f /data/dropbear/ed25519_host_key >/dev/null 2>&1 +dropbear -r /data/dropbear/rsa_host_key -r /data/dropbear/ed25519_host_key -p 22 +echo "[local] sshd up on :22 (ssh root@)" + +# --- RTSP server (Anyka SDK sample): rtsp://:554/vs0 (main), /vs1 (sub) --- +# the binary hard-reads /etc/config/rtsp.ini (ignores argv), so build it there: +# image defaults (/usr/local/rtsp.ini) + your `camcfg` overrides (/data/camcfg.conf) +/usr/sbin/camcfg boot || cp -f /usr/local/rtsp.ini /etc/config/rtsp.ini +# supervised: restarts if it dies (so `killall ak_rtsp_server_sample` = restart). +# touch /tmp/rtsp.stop to stop it for good (fwupdate does). Log: /tmp/rtsp.log (+ .1) +rm -f /tmp/rtsp.stop +( n=0; cd /usr/local + while [ ! -f /tmp/rtsp.stop ]; do + [ -f /tmp/rtsp.log ] && mv -f /tmp/rtsp.log /tmp/rtsp.log.1 + TZ=$(cat /data/timezone 2>/dev/null || cat /usr/local/timezone 2>/dev/null || echo UTC0) \ + ak_rtsp_server_sample >/tmp/rtsp.log 2>&1 + [ -f /tmp/rtsp.stop ] && break + n=$((n+1)); [ $n -gt 5 ] && sleep 60 || sleep 5 # back off if it keeps failing + done ) & +echo "[local] rtsp supervised. URLs: rtsp:///vs0 rtsp:///vs1" + +# --- ONVIF: auto-start once you build + drop binaries into /data/onvif (see RTSP.md) --- +[ -x /data/onvif/onvif_simple_server ] && sh /usr/local/onvif/start_onvif.sh & +EOS +chmod 0755 sbin/local_bootstrap.sh + +# rw helper +cat > sbin/rw <<'EOS' +#!/bin/sh +f=$1; OV=$(cat /tmp/ovroot 2>/dev/null); OV=${OV:-/etc/config/overlay} +[ -z "$f" ] && { echo "usage: rw /abs/path/file (overlay: $OV)"; exit 1; } +mkdir -p "$OV$(dirname "$f")"; [ -e "$OV$f" ] || cp -a "$f" "$OV$f" +mount -o bind "$OV$f" "$f" 2>/dev/null; echo "editable+persistent: $f" +EOS +chmod 0755 sbin/rw +sed -i 's#^service.sh start &#/usr/sbin/local_bootstrap.sh \&#' sbin/main.sh +cd "$HERE" + +"$HERE/repack-fs.sh" "$WORK/app" "$SET/app.bin" $((0x2e0000)) squashfs +# empty jffs2 DATA (2176K) = 4K cleanmarkers (like flash_erase -j) +python3 -Ic " +cm=bytes.fromhex('851903200c000000b1b01ee4'); EB=0x1000 +open('$SET/data.bin','wb').write((cm+b'\xff'*(EB-len(cm)))*((0x220000)//EB))" +LAYOUT="$LAYOUT" "$HERE/build-image.sh" "$SET" "$HERE/out/camera_flash_rtsp.bin" + +# ---- stage everything for flashing (SD card / programmer) ---- +# full.bin whole chip (programmer, or U-Boot full write) - WIPES DATA (settings, SSH keys) +# app.bin dtb.bin data.bin partition writes (GUIDE.md §5/§8); env.bin = the env above +STAGE=${STAGE_DIR:-$HERE/../sdcard} +mkdir -p "$STAGE" +cp -f "$HERE/out/camera_flash_rtsp.bin" "$STAGE/full.bin" +for f in app dtb data env; do cp -f "$SET/$f.bin" "$STAGE/$f.bin"; done +# SD-card-only install for a STOCK camera (stock U-Boot ht_recover_fw.conf, no serial/programmer). +# Stage 1 (U-Boot): writes an installer rootfs = stock rootfs + camerarev-install.sh (type 10). +# Stage 2 (installer, original APP still intact): dumps the full 8 MiB to SD, then writes +# APP+DATA, DTB, the original rootfs and finally the env, and reboots. See IMAGE_CONTENTS.md. +rm -rf "$STAGE/stock-install" +SI="$STAGE/sd-install-backup"; rm -rf "$SI"; mkdir -p "$SI/camerarev" +rm -rf "$WORK/irfs"; unsquashfs -q -d "$WORK/irfs" "$HERE/parts/stock/rootfs.bin" >/dev/null +cp "$HERE/blobs/sdinstall/camerarev-install.sh" "$WORK/irfs/etc/init.d/"; chmod 0755 "$WORK/irfs/etc/init.d/camerarev-install.sh" +python3 - "$WORK/irfs/etc/init.d/rc.local" <<'PY' +import sys +p = sys.argv[1]; s = open(p).read() +# don't mount CONFIG (jffs2 mounts can write; the backup must be pristine) +a = s.index('# mount jffs2 file-system.'); b = s.index('echo "starting mdev..."') +s = s[:a] + s[b:] +a = s.index('#start system service') +s = s[:a] + '# camerarev: run the SD installer instead of the camera app\n/etc/init.d/camerarev-install.sh &\n' +open(p, 'w').write(s) +PY +mksquashfs "$WORK/irfs" "$SI/root.sqsh4" -comp xz -b 131072 -all-root -noappend -no-progress >/dev/null +[ "$(stat -c %s "$SI/root.sqsh4")" -le $((0xfc000)) ] || { echo "installer rootfs too big"; exit 1; } +{ cat "$SET/app.bin"; head -c $((0x2e0000 - $(stat -c %s "$SET/app.bin"))) /dev/zero | tr '\0' '\377' + cat "$SET/data.bin"; } > "$SI/camerarev/usr.sqsh4" +[ "$(stat -c %s "$SI/camerarev/usr.sqsh4")" -eq $((0x500000)) ] || { echo "usr.sqsh4 size wrong"; exit 1; } +head -c $((TS)) "$SET/dtb.bin" > "$SI/camerarev/dtb.bin" +cp "$SET/env.bin" "$SET/envbk.bin" "$SI/camerarev/" +cp "$HERE/parts/stock/rootfs.bin" "$SI/camerarev/rootfs.bin" +cp "$HERE/blobs/fwupdate/mtdflash" "$SI/camerarev/mtdflash" +for p in UBOOT KERNEL ROOTFS; do + f=$(echo $p | tr A-Z a-z); echo "$(md5sum < "$HERE/parts/stock/$f.bin" | cut -d' ' -f1) $p" +done > "$SI/camerarev/ref.md5" +( cd "$SI/camerarev" && md5sum usr.sqsh4 dtb.bin env.bin envbk.bin rootfs.bin mtdflash > MD5SUMS ) +python3 - "$SI/ht_recover_fw.conf" "$FWVER" "$(stat -c %s "$SI/root.sqsh4")" <<'PY' +import struct, sys +# 80-byte header parsed by stock U-Boot: magic[8] type kernel rootfs usrfs check_bundle bundle[36] version[16] +# type digits: hundreds=usr.sqsh4 tens=root.sqsh4 units=uImage -> 10 = rootfs region only +hdr = b'HT_FW'.ljust(8, b'\0') + struct.pack(' MD5SUMS ) +echo "[rtsp.sh] staged in $STAGE: full.bin app.bin dtb.bin data.bin env.bin sd-install-backup/ sd-install-direct/ MD5SUMS (fw $FWVER)"