Files
actionkamera/toolkit/variants/rtsp.sh
T
BRNSystemsandClaude Opus 5.5 64e8a30e5b 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 <noreply@anthropic.com>
2026-11-23 22:01:43 +01:00

359 lines
20 KiB
Bash
Executable File

#!/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:-<none>}"
# 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 <<INI
[record]
# off | continuous | motion | both
mode = ${REC_MODE:-both}
# 0 = main stream (2304x1296), 1 = substream (640x360)
stream = ${REC_STREAM:-0}
continuous_path = /mnt/sd/rec/continuous
motion_path = /mnt/sd/rec/motion
continuous_percent = ${REC_CONT_PERCENT:-70}
motion_percent = ${REC_MOTION_PERCENT:-25}
continuous_max_mb = 0
motion_max_mb = 0
# never let the card get fuller than this (oldest files deleted first)
min_free_mb = 200
segment_seconds = 60
motion_pre_seconds = 5
motion_post_seconds = 10
motion_clip_max_seconds = 300
# 0-100; or set motion_threshold directly (0 = derive from sensitivity)
motion_sensitivity = 50
motion_threshold = 0
motion_min_cells = 4
motion_trigger_frames = 2
# 1 = log motion grid stats every second to /tmp/rtsp.log (for tuning)
motion_debug = 0
# executable called with "start" / "stop" on motion (e.g. MQTT / webhook)
motion_hook = /data/motion_hook.sh
INI
# swap venc kernel modules for the versions matching the SDK userspace libs
# (stock venc V2.0.13 lacks an ioctl that libmpi_venc V3.0.02 needs -> "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 >/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@<ip>)"
# --- RTSP server (Anyka SDK sample): rtsp://<ip>: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://<ip>/vs0 rtsp://<ip>/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('<IIIII', 10, 0, int(sys.argv[3]), 0, 0)
hdr += b'\0' * 36 + sys.argv[2].encode()[:15].ljust(16, b'\0')
assert len(hdr) == 80
open(sys.argv[1], 'wb').write(hdr)
PY
# DIRECT variant: U-Boot writes APP+DATA itself (type 100), the first boot writes DTB + env.
# Fewer moving parts; the backup then lacks the original APP (Tuya firmware).
SD="$STAGE/sd-install-direct"; rm -rf "$SD"; mkdir -p "$SD"
cp "$SI/camerarev/usr.sqsh4" "$SD/usr.sqsh4"
python3 - "$SD/ht_recover_fw.conf" "$FWVER" <<'PY'
import struct, sys
hdr = b'HT_FW'.ljust(8, b'\0') + struct.pack('<IIIII', 100, 0, 0, 0x500000, 0)
hdr += b'\0' * 36 + sys.argv[2].encode()[:15].ljust(16, b'\0')
assert len(hdr) == 80
open(sys.argv[1], 'wb').write(hdr)
PY
( cd "$STAGE" && md5sum full.bin app.bin dtb.bin data.bin env.bin > 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)"