From 980a3e51783f13fae1c755ce19140ba5f7e92510 Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Mon, 23 Nov 2026 12:02:18 +0100 Subject: [PATCH] poc(zone-anpr): live picture, H.264 metrics, one decode thread - /live/.mjpg: the newest decoded frame with the vehicle boxes, re-encoded once for all viewers; idle while nobody watches - the page shows that stream instead of polling a still every 700 ms - metrics: stream codec, seconds to the first picture, viewers, live frames a second, network in - config: decode_threads (CAP_PROP_N_THREADS; 1 removes the frames the H.264 decoder holds back per extra thread), live_quality Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RZgP5oZdzvo92Eouc9eRv5 --- poc/zone-anpr/zone_anpr.py | 99 ++++++++++++++++++++++++++++++++++---- 1 file changed, 90 insertions(+), 9 deletions(-) diff --git a/poc/zone-anpr/zone_anpr.py b/poc/zone-anpr/zone_anpr.py index 8fe2fb2..00c03f3 100644 --- a/poc/zone-anpr/zone_anpr.py +++ b/poc/zone-anpr/zone_anpr.py @@ -338,7 +338,12 @@ class Camera: self.frame_no = 0 self.cond = threading.Condition() self.status = "starting" - self.stats = dict(decoded=0, received=0, snap_ms=0.0, hires=0, hires_ms=0.0, det_runs=0, det_ms=0.0, read_runs=0, read_ms=0.0, saves=0, verdicts=0) + self.stats = dict(decoded=0, received=0, snap_ms=0.0, hires=0, hires_ms=0.0, det_runs=0, det_ms=0.0, read_runs=0, read_ms=0.0, saves=0, verdicts=0, live=0) + # The live picture for the page: every decoded frame re-encoded as JPEG, ONCE per frame + # for all viewers, and only while somebody watches (2026-11-23, the H.264 test). + self.live_viewers, self.live_jpeg, self.live_no = 0, None, 0 + self.live_cond = threading.Condition() + self.codec, self.first_frame_s = None, None # what the camera sends; connect -> first picture self.present = False # One lane, two cameras (entry and exit watch the same lane from both ends): only one # camera may hold a visit at a time. The other YIELDS, and stays yielded until its own @@ -519,21 +524,56 @@ class Camera: # --- stream mode: decode everything, keep the newest def grab_stream(self): if True: - cap = cv2.VideoCapture(self.url, cv2.CAP_FFMPEG) + t0 = time.time() + # FFmpeg decodes H.264 on several threads by default, and each extra thread holds one + # more frame back: 5 frames on the 6-core booth PC, 0.4 s at 12.5 fps (measured + # 2026-11-23). decode_threads: 1 gives each frame out as soon as it is decoded. + n = self.app.cfg.get("decode_threads") + cap = (cv2.VideoCapture(self.url, cv2.CAP_FFMPEG, [cv2.CAP_PROP_N_THREADS, int(n)]) if n + else cv2.VideoCapture(self.url, cv2.CAP_FFMPEG)) if not cap.isOpened(): raise ConnectionError("cannot open stream") self.status = "live" - log(self.name, "stream open", self.safe_url(), + fcc = int(cap.get(cv2.CAP_PROP_FOURCC)) + self.codec = "".join(chr((fcc >> 8 * i) & 0xFF) for i in range(4)).strip("\x00 ") or "?" + log(self.name, "stream open", self.safe_url(), self.codec, int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), "x", int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) + first = True while True: ok, f = cap.read() if not ok: self.status = "stream lost" log(self.name, "stream lost, reconnecting") break + if first: + first, self.first_frame_s = False, round(time.time() - t0, 2) + log(self.name, f"first picture {self.first_frame_s} s after connecting") self.publish(frame=f) cap.release() + # --- live picture: one JPEG per decoded frame, shared by all viewers, idle with none + def live_loop(self): + seen = 0 + q = int(self.app.cfg.get("live_quality", 75)) + while True: + with self.live_cond: + self.live_cond.wait_for(lambda: self.live_viewers > 0) + with self.cond: + self.cond.wait_for(lambda: self.frame_no != seen, timeout=2) + if self.frame_no == seen: + continue + f, _, seen = self.latest() + if f is None: + continue + img = f.copy() # the boxes must not land on the frame the detector and the clip use + for x1, y1, x2, y2, *_ in list(self.last_vehicles): + cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2) + jpeg = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, q])[1].tobytes() + self.stats["live"] += 1 + with self.live_cond: + self.live_jpeg, self.live_no = jpeg, self.live_no + 1 + self.live_cond.notify_all() + # --- worker: presence in zone → plate def work(self): period = 1.0 / self.app.cfg["detect_fps"] @@ -1273,14 +1313,24 @@ class App: a = list(map(int, open("/proc/stat").readline().split()[1:])) return sum(a), a[3] + a[4] + def net_rx(): # bytes received on the machine's real network cards (host network) + n = 0 + for ln in open("/proc/net/dev").read().splitlines()[2:]: + name, rest = ln.split(":", 1) + if name.strip().startswith(("en", "eth", "wl")): + n += int(rest.split()[0]) + return n + cpu0, _ = proc() h0 = host() + n0 = net_rx() t0 = time.time() prev = {c.name: dict(c.stats) for c in self.cams} while True: time.sleep(self.cfg["metrics_s"]) cpu1, rss = proc() h1 = host() + n1 = net_rx() t1 = time.time() dt = t1 - t0 tot, idle = h1[0] - h0[0], h1[1] - h0[1] @@ -1288,12 +1338,15 @@ class App: proc_cores=round((cpu1 - cpu0) / dt, 2), proc_pct_of_host=round(100 * (cpu1 - cpu0) / dt / NCPU, 1), host_busy_pct=round(100 * (tot - idle) / tot, 1) if tot else None, - rss_mb=round(rss / 2**20), load1=os.getloadavg()[0], cams={}) + rss_mb=round(rss / 2**20), load1=os.getloadavg()[0], + net_rx_mbps=round((n1 - n0) * 8 / dt / 1e6, 2), cams={}) for c in self.cams: s, p = c.stats, prev[c.name] d = {k: s[k] - p[k] for k in s} m["cams"][c.name] = dict( - status=c.status, mode=c.mode, fps=round(d["received"] / dt, 1), + status=c.status, mode=c.mode, codec=c.codec, first_frame_s=c.first_frame_s, + live_viewers=c.live_viewers, live_per_s=round(d["live"] / dt, 1), + fps=round(d["received"] / dt, 1), decoded_per_s=round(d["decoded"] / dt, 1), snap_ms=round(d["snap_ms"] / d["received"], 1) if c.mode == "snapshot" and d["received"] else None, det_per_s=round(d["det_runs"] / dt, 1), @@ -1303,12 +1356,12 @@ class App: read_ms=round(d["read_ms"] / d["read_runs"], 1) if d["read_runs"] else None, saves=d["saves"], verdicts=d["verdicts"], present=c.present) prev[c.name] = dict(s) - cpu0, h0, t0 = cpu1, h1, t1 + cpu0, h0, n0, t0 = cpu1, h1, n1, t1 with self.io_lock, open(self.out / "metrics.jsonl", "a") as fh: fh.write(json.dumps(m) + "\n") log("metrics", f"proc {m['proc_cores']} cores ({m['proc_pct_of_host']}% of host)", - f"rss {m['rss_mb']} MB", f"host {m['host_busy_pct']}%", - " | ".join(f"{n}: {v['mode']} {v['fps']} in/s, {v['decoded_per_s']} dec/s" + f"rss {m['rss_mb']} MB", f"host {m['host_busy_pct']}%", f"net in {m['net_rx_mbps']} Mbps", + " | ".join(f"{n}: {v['mode']} {v['codec']} {v['fps']} in/s, {v['decoded_per_s']} dec/s, live {v['live_per_s']}/s x{v['live_viewers']}" + (f", snap {v['snap_ms']} ms" if v['snap_ms'] else "") + f", det {v['det_ms']} ms, reads {v['reads']}" + (f" (hi-res {v['hires_ms']} ms)" if v['hires_ms'] else "") + "" f" @ {v['read_ms']} ms" for n, v in m["cams"].items())) @@ -1317,6 +1370,7 @@ class App: for c in self.cams: threading.Thread(target=c.grab, daemon=True, name=f"grab-{c.name}").start() threading.Thread(target=c.work, daemon=True, name=f"work-{c.name}").start() + threading.Thread(target=c.live_loop, daemon=True, name=f"live-{c.name}").start() threading.Thread(target=self.metrics, daemon=True, name="metrics").start() Handler.app = self srv = ThreadingHTTPServer(("0.0.0.0", self.cfg["http_port"]), Handler) @@ -1391,7 +1445,7 @@ async function saveZone(n){const z=S.zone[n]||[];if(z.length<3)return alert('Nee await fetch('zone/'+n,{method:'POST',body:JSON.stringify(z)});S.zone[n]=[];last=await (await fetch('status')).json();draw()} async function tick(){ try{last=await (await fetch('status')).json(); - for(const c of last.cams){document.getElementById('i-'+c.name).src='frame/'+c.name+'.jpg?'+Date.now(); + for(const c of last.cams){{const im=document.getElementById('i-'+c.name);if(!im.dataset.live){im.dataset.live=1;im.onerror=()=>{delete im.dataset.live};im.src='live/'+c.name+'.mjpg?'+Date.now()}} document.getElementById('s-'+c.name).textContent=`${c.status} · ${c.present?'ZONE BUSY'+(c.crossing?' · last crossing '+({'a-to-b':'A → B (in)','b-to-a':'B → A (out)'})[c.crossing]:' · no crossing yet'):c.yielded?'lane busy (other camera)':c.busy?'vehicle in zone (no visit)':'empty'}${c.side?' · car '+({a:'on side A',b:'on side B',line:'on the line'})[c.side]:''}${c.read?' · '+c.read:''}`} const R=last.relays;relaybar.innerHTML=!R.configured?'Relays: not configured': (R.armed?`RELAYS ARMED — R1 opens on a car in the zone. R2 (close) ${R.close_live?'is LIVE: it closes the real barrier on an abandoned open':'stays a dry run (logged only)'}. Auto-disarm in ${Math.ceil(R.armed_left_s/60)} min. ` @@ -1466,6 +1520,33 @@ class Handler(BaseHTTPRequestHandler): return self.send(200, json.dumps(dict(cams=cams, reads=reads, visits=visits, relays=relays)).encode(), "application/json") if self.path == "/relaystatus": # a status read on demand: moves nothing return self.send(200, json.dumps(a.relays.status()).encode(), "application/json") + m = re.match(r"^/live/([\w-]+)\.mjpg", self.path) + if m: # the live picture: multipart JPEG, newest frame only (a slow viewer skips frames) + c = next((c for c in a.cams if c.name == m.group(1)), None) + if c is None: + return self.send(404, b"no camera", "text/plain") + self.send_response(200) + self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=frame") + self.send_header("Cache-Control", "no-store") + self.end_headers() + with c.live_cond: + c.live_viewers += 1 + c.live_cond.notify_all() + seen = c.live_no + try: + while True: + with c.live_cond: + if not c.live_cond.wait_for(lambda: c.live_no != seen, timeout=10): + continue + jpeg, seen = c.live_jpeg, c.live_no + self.wfile.write(b"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: " + + str(len(jpeg)).encode() + b"\r\n\r\n" + jpeg + b"\r\n") + except OSError: + pass # the viewer went away + finally: + with c.live_cond: + c.live_viewers -= 1 + return m = re.match(r"^/frame/([\w-]+)\.jpg", self.path) if m: c = next((c for c in a.cams if c.name == m.group(1)), None)