Camera: reuse ISP scratch buffers and fix video start frame
CI / test (push) Failing after 49s

- Reuse per-state scratch buffers in the Quad Bayer ISP path to cut per-frame allocations; never return an alias to the scratch output
- Release memoryviews and run gc before closing mmaps
- Seed recording from latest_frame() and emit it on stop if no fresh frame arrived, so short clips still produce a valid MP4
- Drop the initial push of the start frame
- Lower H.264 CRF from 20 to 23
- Compute ISP stats on a coarser subsample (//96 instead of //160)
This commit is contained in:
nandi committed 2026-11-28 19:37:05 -08:00
1 parent 6cb0562654
commit ebdd330eb5
1 file changed
+97 -38
+97 -38
View File
@@ -6,6 +6,7 @@ import ctypes
from dataclasses import dataclass from dataclasses import dataclass
import datetime import datetime
import fcntl import fcntl
import gc
import glob import glob
import os import os
import queue import queue
@@ -769,7 +770,7 @@ class ContrastAF:
class QuadISPState: class QuadISPState:
"""Temporally smoothed black level, AWB gains, and exposure boost for flicker-free video.""" """Temporally smoothed black level, AWB gains, exposure boost, and reusable scratch buffers."""
def __init__(self, alpha=0.18): def __init__(self, alpha=0.18):
self.alpha = float(alpha) self.alpha = float(alpha)
@@ -777,12 +778,36 @@ class QuadISPState:
self.black = 0.0 self.black = 0.0
self.gains = None self.gains = None
self.boost = 1.0 self.boost = 1.0
self._bgr16_raw_buf = None
self._bgr16_crop_buf = None
self._bgr8_buf = None
def reset(self): def reset(self):
self.initialized = False self.initialized = False
self.black = 0.0 self.black = 0.0
self.gains = None self.gains = None
self.boost = 1.0 self.boost = 1.0
self._bgr16_raw_buf = None
self._bgr16_crop_buf = None
self._bgr8_buf = None
def get_bgr16_raw(self, h, w, np_mod):
shape = (h, w, 3)
if self._bgr16_raw_buf is None or self._bgr16_raw_buf.shape != shape:
self._bgr16_raw_buf = np_mod.empty(shape, dtype=np_mod.uint16)
return self._bgr16_raw_buf
def get_bgr16_crop(self, h, w, np_mod):
shape = (h, w, 3)
if self._bgr16_crop_buf is None or self._bgr16_crop_buf.shape != shape:
self._bgr16_crop_buf = np_mod.empty(shape, dtype=np_mod.uint16)
return self._bgr16_crop_buf
def get_bgr8(self, h, w, np_mod):
shape = (h, w, 3)
if self._bgr8_buf is None or self._bgr8_buf.shape != shape:
self._bgr8_buf = np_mod.empty(shape, dtype=np_mod.uint8)
return self._bgr8_buf
def update(self, black, gains, boost, np_mod): def update(self, black, gains, boost, np_mod):
g = np_mod.asarray(gains, dtype=np_mod.float32) g = np_mod.asarray(gains, dtype=np_mod.float32)
@@ -802,7 +827,7 @@ class QuadISPState:
def _compute_quad_stats_and_gains(bgr16, max_val, black_cap, np_mod): def _compute_quad_stats_and_gains(bgr16, max_val, black_cap, np_mod):
"""Compute black level, midtone-weighted AWB gains, raw luma percentiles, and digital boost.""" """Compute black level, midtone-weighted AWB gains, raw luma percentiles, and digital boost."""
fh, fw = bgr16.shape[:2] fh, fw = bgr16.shape[:2]
step = max(1, min(fh, fw) // 160) step = max(1, min(fh, fw) // 96)
sub16 = bgr16[::step, ::step].astype(np_mod.float32) sub16 = bgr16[::step, ::step].astype(np_mod.float32)
if fh > 32 and fw > 32: if fh > 32 and fw > 32:
border_m = max(1, 8 // step) border_m = max(1, 8 // step)
@@ -904,6 +929,7 @@ def quad_raw_to_bgr16(
offset=0, offset=0,
target_size=(1152, 864), target_size=(1152, 864),
high_quality=False, high_quality=False,
isp_state=None,
cv2_mod=None, cv2_mod=None,
np_mod=None, np_mod=None,
): ):
@@ -919,39 +945,48 @@ def quad_raw_to_bgr16(
even_h = (height // 2) * 2 even_h = (height // 2) * 2
even_w = (width // 4) * 4 even_w = (width // 4) * 4
isp = load_isp_lib() isp = load_isp_lib()
use_scratch = (isp_state is not None) and (not high_quality)
can_4x4 = (not high_quality) and (target_size is not None) and (even_w // 4 >= target_size[0] and even_h // 4 >= target_size[1]) try:
if can_4x4: can_4x4 = (not high_quality) and (target_size is not None) and (even_w // 4 >= target_size[0] and even_h // 4 >= target_size[1])
w4 = even_w // 4 if can_4x4:
h4 = even_h // 4 w4 = even_w // 4
h4 = even_h // 4
if isp is not None:
bgr16 = isp_state.get_bgr16_raw(h4, w4, np_mod) if use_scratch else np_mod.empty((h4, w4, 3), dtype=np_mod.uint16)
isp.quad_csi2p_to_bgr16_4x4(arr.ctypes.data, even_w, even_h, stride, bgr16.ctypes.data)
else:
bgr16 = _unpack_quad_4x4_numpy(arr, even_w, even_h, np_mod)
tw, th = int(target_size[0]), int(target_size[1])
if tw == w4 and th == h4:
pass
elif (w4 - tw) <= 32 and (h4 - th) <= 32 and w4 >= tw and h4 >= th:
dx = (w4 - tw) // 2
dy = (h4 - th) // 2
if use_scratch:
crop_dst = isp_state.get_bgr16_crop(th, tw, np_mod)
np_mod.copyto(crop_dst, bgr16[dy:dy + th, dx:dx + tw])
bgr16 = crop_dst
else:
bgr16 = np_mod.ascontiguousarray(bgr16[dy:dy + th, dx:dx + tw])
else:
bgr16 = cv2_mod.resize(bgr16, (tw, th), interpolation=cv2_mod.INTER_AREA)
return bgr16
# 2x2 10-bit Bayer path (for HQ stills or explicit target sizes larger than 4x4 supercell).
if isp is not None: if isp is not None:
bgr16 = np_mod.empty((h4, w4, 3), dtype=np_mod.uint16) bayer = np_mod.empty((even_h // 2, even_w // 2), dtype=np_mod.uint16)
isp.quad_csi2p_to_bgr16_4x4(arr.ctypes.data, even_w, even_h, stride, bgr16.ctypes.data) isp.quad_csi2p_to_bayer16_2x2(arr.ctypes.data, even_w, even_h, stride, bayer.ctypes.data)
else: else:
bgr16 = _unpack_quad_4x4_numpy(arr, even_w, even_h, np_mod) bayer = _unpack_quad_2x2_numpy(arr, even_w, even_h, np_mod)
tw, th = int(target_size[0]), int(target_size[1])
if tw == w4 and th == h4:
pass
elif (w4 - tw) <= 32 and (h4 - th) <= 32 and w4 >= tw and h4 >= th:
dx = (w4 - tw) // 2
dy = (h4 - th) // 2
bgr16 = np_mod.ascontiguousarray(bgr16[dy:dy + th, dx:dx + tw])
else:
bgr16 = cv2_mod.resize(bgr16, (tw, th), interpolation=cv2_mod.INTER_AREA)
return bgr16
# 2x2 10-bit Bayer path (for HQ stills or explicit target sizes larger than 4x4 supercell). demosaic_code = getattr(cv2_mod, "COLOR_BayerBG2BGR_EA", cv2_mod.COLOR_BayerBG2BGR) if high_quality else cv2_mod.COLOR_BayerBG2BGR
if isp is not None: bgr16 = cv2_mod.cvtColor(bayer, demosaic_code)
bayer = np_mod.empty((even_h // 2, even_w // 2), dtype=np_mod.uint16) if target_size is not None and (bgr16.shape[1], bgr16.shape[0]) != (int(target_size[0]), int(target_size[1])):
isp.quad_csi2p_to_bayer16_2x2(arr.ctypes.data, even_w, even_h, stride, bayer.ctypes.data) bgr16 = cv2_mod.resize(bgr16, (int(target_size[0]), int(target_size[1])), interpolation=cv2_mod.INTER_AREA)
else: return np_mod.ascontiguousarray(bgr16)
bayer = _unpack_quad_2x2_numpy(arr, even_w, even_h, np_mod) finally:
del arr
demosaic_code = getattr(cv2_mod, "COLOR_BayerBG2BGR_EA", cv2_mod.COLOR_BayerBG2BGR) if high_quality else cv2_mod.COLOR_BayerBG2BGR
bgr16 = cv2_mod.cvtColor(bayer, demosaic_code)
if target_size is not None and (bgr16.shape[1], bgr16.shape[0]) != (int(target_size[0]), int(target_size[1])):
bgr16 = cv2_mod.resize(bgr16, (int(target_size[0]), int(target_size[1])), interpolation=cv2_mod.INTER_AREA)
return np_mod.ascontiguousarray(bgr16)
def isp_finish_bgr16( def isp_finish_bgr16(
@@ -985,8 +1020,13 @@ def isp_finish_bgr16(
isp = load_isp_lib() isp = load_isp_lib()
bgr16_c = np_mod.ascontiguousarray(bgr16, dtype=np_mod.uint16) bgr16_c = np_mod.ascontiguousarray(bgr16, dtype=np_mod.uint16)
h, w = bgr16_c.shape[:2] h, w = bgr16_c.shape[:2]
scratch_out = None
if isp is not None: if isp is not None:
out = np_mod.empty((h, w, 3), dtype=np_mod.uint8) if isp_state is not None and not high_quality:
out = isp_state.get_bgr8(h, w, np_mod)
scratch_out = out
else:
out = np_mod.empty((h, w, 3), dtype=np_mod.uint8)
isp.isp_ccm_tone_bgr16_to_bgr8( isp.isp_ccm_tone_bgr16_to_bgr8(
bgr16_c.ctypes.data, bgr16_c.ctypes.data,
out.ctypes.data, out.ctypes.data,
@@ -1016,7 +1056,12 @@ def isp_finish_bgr16(
blur = cv2_mod.GaussianBlur(out, (0, 0), 1.2) blur = cv2_mod.GaussianBlur(out, (0, 0), 1.2)
out = cv2_mod.addWeighted(out, 1.18, blur, -0.18, 0) out = cv2_mod.addWeighted(out, 1.18, blur, -0.18, 0)
res = np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) rot_res = rotate_bgr(out, rot, cv2_mod)
# Never return an alias to isp_state._bgr8_buf because callers retain frames for preview/video.
if scratch_out is not None and rot_res is scratch_out:
res = rot_res.copy()
else:
res = np_mod.ascontiguousarray(rot_res)
if return_stats: if return_stats:
return res, (raw_p50, raw_p95) return res, (raw_p50, raw_p95)
return res return res
@@ -1053,6 +1098,7 @@ def debayer_quad_csi2p(
offset=offset, offset=offset,
target_size=target_size, target_size=target_size,
high_quality=high_quality, high_quality=high_quality,
isp_state=isp_state,
cv2_mod=cv2_mod, cv2_mod=cv2_mod,
np_mod=np_mod, np_mod=np_mod,
) )
@@ -1402,6 +1448,8 @@ class CameraEngine:
return entry[0] return entry[0]
def _close_mmaps(self): def _close_mmaps(self):
if self._mapped_fds:
gc.collect()
for mm, _sz in self._mapped_fds.values(): for mm, _sz in self._mapped_fds.values():
try: try:
mm.close() mm.close()
@@ -1665,6 +1713,7 @@ class CameraEngine:
offset=plane.offset, offset=plane.offset,
target_size=target_size, target_size=target_size,
high_quality=high_quality, high_quality=high_quality,
isp_state=None if high_quality else self._isp_state,
cv2_mod=self.cv2, cv2_mod=self.cv2,
np_mod=self.np, np_mod=self.np,
) )
@@ -1695,6 +1744,7 @@ class CameraEngine:
ts_ns = self._extract_req_ts_ns(req, buf) ts_ns = self._extract_req_ts_ns(req, buf)
mm = self._get_mmap(plane) mm = self._get_mmap(plane)
self._dma_sync(plane.fd, DMA_BUF_SYNC_START_READ) self._dma_sync(plane.fd, DMA_BUF_SYNC_START_READ)
mv = None
try: try:
mv = memoryview(mm)[plane.offset:plane.offset + plane.length] mv = memoryview(mm)[plane.offset:plane.offset + plane.length]
frame = convert_frame( frame = convert_frame(
@@ -1708,6 +1758,9 @@ class CameraEngine:
np_mod=self.np, np_mod=self.np,
) )
finally: finally:
if mv is not None:
mv.release()
del mv
self._dma_sync(plane.fd, DMA_BUF_SYNC_END_READ) self._dma_sync(plane.fd, DMA_BUF_SYNC_END_READ)
self._requeue(req) self._requeue(req)
req = None req = None
@@ -1983,9 +2036,7 @@ class CameraEngine:
"""Start recording exact-PTS VFR H.264 MP4 via Matroska I420 pipe to ffmpeg.""" """Start recording exact-PTS VFR H.264 MP4 via Matroska I420 pipe to ffmpeg."""
if shutil.which("ffmpeg") is None: if shutil.which("ffmpeg") is None:
raise RuntimeError("ffmpeg is not installed") raise RuntimeError("ffmpeg is not installed")
with self._lock: frame, _ = self.latest_frame()
frame = self._latest_bgr
init_ts_ns = self._latest_ts_ns
if frame is None: if frame is None:
raise RuntimeError("camera is still warming up") raise RuntimeError("camera is still warming up")
even = ensure_even_frame(frame) even = ensure_even_frame(frame)
@@ -2028,7 +2079,7 @@ class CameraEngine:
"-preset", "-preset",
"superfast", "superfast",
"-crf", "-crf",
"20", "23",
"-bf", "-bf",
"0", "0",
"-threads", "-threads",
@@ -2099,7 +2150,6 @@ class CameraEngine:
self._rec_duration_ms = 0 self._rec_duration_ms = 0
self._rec_size = (w, h) self._rec_size = (w, h)
wt.start() wt.start()
self._push_video_frame(frame, init_ts_ns or time.monotonic_ns())
return dst_path return dst_path
def _push_video_frame(self, frame, ts_ns=None): def _push_video_frame(self, frame, ts_ns=None):
@@ -2152,6 +2202,15 @@ class CameraEngine:
if proc is None: if proc is None:
return None, 0 return None, 0
# If stopped before a fresh frame arrived from _run_loop, emit latest frame so MP4 is valid.
if frames == 0:
fb, _ = self.latest_frame()
if fb is not None and q is not None:
try:
q.put_nowait((fb, time.monotonic_ns()))
frames += 1
except Exception:
pass
if q is not None: if q is not None:
# Wait briefly for room if queue is completely full so we never drop the sentinel. # Wait briefly for room if queue is completely full so we never drop the sentinel.
try: try: