diff --git a/backend_py/requirements.txt b/backend_py/requirements.txt index 5cec6d30..f7188622 100644 --- a/backend_py/requirements.txt +++ b/backend_py/requirements.txt @@ -9,3 +9,5 @@ sdbus==0.14.0 sdbus-networkmanager==2.0.0 pyserial colorlog==6.10.1 +# 2.x requires libjpeg-turbo 3, which Debian 12 and Ubuntu 22.04 do not have +PyTurboJPEG==1.8.3 diff --git a/backend_py/src/models/__init__.py b/backend_py/src/models/__init__.py index 1c6096fd..3c513a44 100644 --- a/backend_py/src/models/__init__.py +++ b/backend_py/src/models/__init__.py @@ -23,6 +23,7 @@ StreamFormatModel, StreamInfoModel, StreamModel, + StreamScale, StreamTypeEnum, UVCControlModel, V4LControlTypeEnum, @@ -81,6 +82,7 @@ "StreamFormatModel", "StreamInfoModel", "StreamModel", + "StreamScale", "StreamTypeEnum", "UVCControlModel", "V4LControlTypeEnum", diff --git a/backend_py/src/models/cameras.py b/backend_py/src/models/cameras.py index b24e5714..e4fdd477 100644 --- a/backend_py/src/models/cameras.py +++ b/backend_py/src/models/cameras.py @@ -6,6 +6,7 @@ """ from enum import Enum, IntEnum +from typing import Literal from pydantic import BaseModel, Field @@ -47,6 +48,11 @@ class StreamTypeEnum(str, Enum): RECORDING = "RECORDING" +# Fraction of the recorded resolution a synchronized recording is streamed at +# (1 = full size, 2 = half, ...) +StreamScale = Literal[1, 2, 4, 8] + + class H264Mode(IntEnum): """ H.264 Mode Enum @@ -161,6 +167,7 @@ class StreamModel(BaseModel): height: int interval: IntervalModel enabled: bool + stream_scale: StreamScale = 1 class Config: from_attributes = True @@ -230,6 +237,7 @@ class StreamInfoModel(BaseModel): encode_type: StreamEncodeTypeEnum enabled: bool endpoints: list[StreamEndpointModel] + stream_scale: StreamScale = 1 class Config: from_attributes = True diff --git a/backend_py/src/models/saved_cameras.py b/backend_py/src/models/saved_cameras.py index 8f94b735..06fecf8d 100644 --- a/backend_py/src/models/saved_cameras.py +++ b/backend_py/src/models/saved_cameras.py @@ -13,6 +13,7 @@ IntervalModel, StreamEncodeTypeEnum, StreamEndpointModel, + StreamScale, StreamTypeEnum, ) @@ -35,6 +36,7 @@ class SavedStreamModel(BaseModel): height: int interval: IntervalModel enabled: bool + stream_scale: StreamScale = 1 class Config: # use_enum_values = True diff --git a/backend_py/src/services/cameras/device_manager.py b/backend_py/src/services/cameras/device_manager.py index bb57c284..2a70ce65 100644 --- a/backend_py/src/services/cameras/device_manager.py +++ b/backend_py/src/services/cameras/device_manager.py @@ -226,11 +226,12 @@ def configure_device_stream(self, stream_info: StreamInfoModel) -> bool: encode_type: StreamEncodeTypeEnum = stream_info.encode_type stream_type: StreamTypeEnum = stream_info.stream_type endpoints = stream_info.endpoints + stream_scale = stream_info.stream_scale # For DWVO streams only: - # Endpoints are read live while recording, so changing only them must not - # restart the stream and split the recording into a new file - only_endpoints_changed = ( + # Endpoints and stream scale are read live while recording, so changing only + # them must not restart the stream and split the recording into a new file + only_live_settings_changed = ( device.stream_runner.started and device.stream.stream_type == StreamTypeEnum.RECORDING and stream_type == StreamTypeEnum.RECORDING @@ -241,7 +242,7 @@ def configure_device_stream(self, stream_info: StreamInfoModel) -> bool: ) device.configure_stream( - encode_type, width, height, interval, stream_type, endpoints + encode_type, width, height, interval, stream_type, endpoints, stream_scale ) should_start = stream_info.enabled @@ -261,8 +262,8 @@ def configure_device_stream(self, stream_info: StreamInfoModel) -> bool: if should_start: # We don't restart the stream if it's a dwvo stream that is also recording - # and only changed its endpoints - if not only_endpoints_changed: + # and only changed its endpoints or stream scale + if not only_live_settings_changed: device.start_stream() else: device.stop_stream() diff --git a/backend_py/src/services/cameras/drivers/device.py b/backend_py/src/services/cameras/drivers/device.py index 624a0a9a..b7bb8e8d 100644 --- a/backend_py/src/services/cameras/drivers/device.py +++ b/backend_py/src/services/cameras/drivers/device.py @@ -221,6 +221,7 @@ def configure_stream( interval: IntervalModel, stream_type: StreamTypeEnum, stream_endpoints: list[StreamEndpointModel] | None = None, + stream_scale: int = 1, ) -> None: if stream_endpoints is None: stream_endpoints = [] @@ -251,6 +252,7 @@ def configure_stream( self.stream.height = height self.stream.interval = interval self.stream.endpoints = stream_endpoints + self.stream.stream_scale = stream_scale self.stream.encode_type = encode_type self.stream.stream_type = stream_type @@ -321,6 +323,7 @@ def load_settings(self, saved_device: SavedDeviceModel) -> None: saved_device.stream.interval, saved_device.stream.stream_type, saved_device.stream.endpoints, + saved_device.stream.stream_scale, ) with self._configuration_lock: diff --git a/backend_py/src/services/cameras/stream_engines/stream.py b/backend_py/src/services/cameras/stream_engines/stream.py index 77c98aa1..95de6a20 100644 --- a/backend_py/src/services/cameras/stream_engines/stream.py +++ b/backend_py/src/services/cameras/stream_engines/stream.py @@ -26,6 +26,8 @@ class Stream: default_factory=lambda: IntervalModel(numerator=1, denominator=30) ) enabled: bool = False + # Synchronized recordings stream at 1/stream_scale of the recorded resolution + stream_scale: int = 1 # Configuration specific software_h264_bitrate: int = 5000 diff --git a/backend_py/src/services/cameras/stream_engines/synchronized_stream_engine.py b/backend_py/src/services/cameras/stream_engines/synchronized_stream_engine.py index b149013d..cc5d34b8 100644 --- a/backend_py/src/services/cameras/stream_engines/synchronized_stream_engine.py +++ b/backend_py/src/services/cameras/stream_engines/synchronized_stream_engine.py @@ -17,6 +17,7 @@ DWVOVideoFrame, DWVOWriter, ) +from ..synchronized_camera.jpeg_scaler import AutoJpegScaler from .base_stream_engine import BaseStreamEngine # How much video a recording can buffer while the disk catches up @@ -72,9 +73,7 @@ def __init__(self, streams, error_callback) -> None: self.emit_error(e.strerror) # Custom RTP improves performance compared to RTP class - def _send_frame( - self, frames: list[CopiedFrame], endpoint: StreamEndpointModel - ) -> None: + def _send_frame(self, frames: list[bytes], endpoint: StreamEndpointModel) -> None: # TODO: change protocol to handle more than two cameras if len(frames) > 2: self.logger.warning( @@ -87,10 +86,10 @@ def _send_frame( right_frame = frames[1] # payload headers - frame_header = struct.pack(" None: self.synchronized_camera.stop() def stream_loop_(self) -> None: - while self._running: - try: - endpoint = self.streams[0].endpoints[0] - except IndexError: - time.sleep(1) - continue - # TODO: do not assume two - try: - (left, right) = self.stream_queue.popleft() + # Only created once a frame needs scaling, since the hardware scaler runs + # its own process + scaler: AutoJpegScaler | None = None + try: + while self._running: + try: + endpoint = self.streams[0].endpoints[0] + except IndexError: + time.sleep(1) + continue + # TODO: do not assume two + try: + (left, right) = self.stream_queue.popleft() + except IndexError: + time.sleep(1 / self.streams[0].interval.denominator) + continue + + # Read live, so it can change without splitting the recording. + # Only the stream is scaled, the recording keeps the full frames + scale = self.streams[0].stream_scale if self.is_recording else 1 + frames = [left.data, right.data] + if scale > 1: + if scaler is None: + scaler = AutoJpegScaler() + frames = [ + scaler.scale(frame.data, frame.width, frame.height, scale) + for frame in (left, right) + ] # TODO: make less scuffed - self._send_frame([left, right], endpoint) - except IndexError: - time.sleep(1 / self.streams[0].interval.denominator) - continue + self._send_frame(frames, endpoint) + finally: + if scaler is not None: + scaler.close() def record_loop_(self) -> None: leader = self.streams[0] diff --git a/backend_py/src/services/cameras/synchronized_camera/jpeg_scaler.py b/backend_py/src/services/cameras/synchronized_camera/jpeg_scaler.py new file mode 100644 index 00000000..cf43b025 --- /dev/null +++ b/backend_py/src/services/cameras/synchronized_camera/jpeg_scaler.py @@ -0,0 +1,379 @@ +""" +jpeg_scaler.py + +Shrinks JPEG frames by a whole factor, so a synchronized camera can stream at a +fraction of the resolution it records at. The hardware JPEG codec is used when the +platform has one (Jetson), and libjpeg-turbo is used everywhere else +""" + +from __future__ import annotations + +import functools +import logging +import queue +import shutil +import subprocess +import threading +from abc import ABC, abstractmethod +from typing import BinaryIO + +# Factors libjpeg-turbo can decode to directly, without a full size decode +SUPPORTED_SCALES = (1, 2, 4, 8) + +# Placeholder for a frame without a quantization table, which cannot be decoded +# anyway, so it never decides the quality of a real frame +DEFAULT_JPEG_QUALITY = 90 + +# Standard JPEG luminance quantization table (Annex K), in zigzag order like DQT +_STD_LUMA_TABLE = ( + 16, 11, 12, 14, 12, 10, 16, 14, 13, 14, 18, 17, 16, 19, 24, 40, + 26, 24, 22, 22, 24, 49, 35, 37, 29, 40, 58, 51, 61, 60, 57, 51, + 56, 55, 64, 72, 92, 78, 64, 68, 87, 69, 55, 56, 80, 109, 81, 87, + 95, 98, 103, 104, 103, 62, 77, 113, 121, 112, 100, 120, 92, 101, 103, 99, +) # fmt: skip + +logger = logging.getLogger("dwe_os_2.cameras.JpegScaler") + + +def scaled_size(width: int, height: int, scale: int) -> tuple[int, int]: + """Size of a frame after scaling, rounded up the same way libjpeg-turbo does""" + return (-(-width // scale), -(-height // scale)) + + +def estimate_quality(data: bytes) -> int: + """ + Quality (1-100) the frame was encoded at, so it can be re-encoded without + losing more than the resolution. Cameras change quality from frame to frame, + so this is read from every frame + """ + table = _luma_table(data) + if table is None: + return DEFAULT_JPEG_QUALITY + return _quality_of_table(table) + + +def _luma_table(data: bytes) -> tuple[int, ...] | None: + """The first quantization table (luminance) of a JPEG, in zigzag order""" + i = 2 # Skip SOI + while i + 4 <= len(data) and data[i] == 0xFF: + marker = data[i + 1] + length = int.from_bytes(data[i + 2 : i + 4], "big") + # Tables always come before the start of scan + if marker == 0xDA: + return None + if marker == 0xDB: + precision = data[i + 4] >> 4 + start = i + 5 + size = 2 if precision else 1 + if start + 64 * size > len(data): + return None + return tuple( + int.from_bytes(data[start + size * k : start + size * (k + 1)], "big") + for k in range(64) + ) + i += 2 + length + return None + + +@functools.lru_cache(maxsize=256) +def _quality_of_table(table: tuple[int, ...]) -> int: + # Cameras reuse a few tables, so the fit is cached by table + def libjpeg_table(quality: int) -> tuple[int, ...]: + scale = 5000 // quality if quality < 50 else 200 - 2 * quality + return tuple(min(max((v * scale + 50) // 100, 1), 255) for v in _STD_LUMA_TABLE) + + # The quality whose libjpeg table is closest to the camera's + def distance(quality: int) -> int: + pairs = zip(libjpeg_table(quality), table, strict=True) + return sum(abs(a - b) for a, b in pairs) + + return min(range(1, 101), key=distance) + + +class JpegScaler(ABC): + name: str + + @abstractmethod + def scale( + self, data: bytes, width: int, height: int, scale: int, quality: int + ) -> bytes: + """Return the JPEG in data shrunk to 1/scale of width and height""" + + def close(self) -> None: # noqa: B027 - most scalers have nothing to clean up + pass + + +class TurboJpegScaler(JpegScaler): + """ + Decodes straight to the reduced size in the DCT domain and re-encodes from YUV, + which keeps the cost low enough for the CPU + """ + + name = "libjpeg-turbo (software)" + + def __init__(self) -> None: + # Imported here so a missing libturbojpeg only disables scaling + from turbojpeg import TurboJPEG + + self._turbo = TurboJPEG() + + def scale( + self, data: bytes, width: int, height: int, scale: int, quality: int + ) -> bytes: + return self._turbo.scale_with_quality( + data, scaling_factor=(1, scale), quality=quality + ) + + +class GStreamerJpegScaler(JpegScaler): + """ + Scales with a hardware JPEG codec through a gst-launch process that stays + running. Frames are written to stdin and read from stdout as multipart parts, + which carry their length, so every frame comes back on its own and in order + """ + + name = "GStreamer" + + BOUNDARY = b"dweframe" + # A frame that takes longer than this means the pipeline is stuck + TIMEOUT_S = 1.0 + # The first frame also waits for the pipeline and codec to start + STARTUP_TIMEOUT_S = 5.0 + + def __init__( + self, + decoder: str, + converter: str, + encoder: str, + raw_caps: str = "video/x-raw", + ) -> None: + self._decoder = decoder + self._converter = converter + self._encoder = encoder + self._raw_caps = raw_caps + + self._process: subprocess.Popen[bytes] | None = None + self._frames: queue.Queue[bytes | None] = queue.Queue() + # Input and output sizes the running pipeline was built for + self._sizes: tuple[int, int, int, int] | None = None + # Encoder quality of the running pipeline + self._quality = 0 + + @classmethod + def jetson(cls) -> GStreamerJpegScaler: + scaler = cls( + "nvjpegdec", + "nvvidconv", + "nvjpegenc", + raw_caps="video/x-raw(memory:NVMM)", + ) + scaler.name = "Jetson nvjpeg (hardware)" + return scaler + + @staticmethod + def has_elements(*elements: str) -> bool: + return _has_gstreamer_elements(elements) + + def scale( + self, data: bytes, width: int, height: int, scale: int, quality: int + ) -> bytes: + out_width, out_height = scaled_size(width, height, scale) + # Raw video has to be an even size + out_width += out_width % 2 + out_height += out_height % 2 + + sizes = (width, height, out_width, out_height) + timeout = self.TIMEOUT_S + # The encoder quality is fixed once the pipeline runs, so it restarts for + # higher quality frames and never encodes below the source. Lower quality + # frames keep the pipeline, since restarting on every change is too slow + if self._process is None or self._sizes != sizes or quality > self._quality: + self._quality = max(quality, self._quality) + self._start(out_width, out_height) + self._sizes = sizes + timeout = self.STARTUP_TIMEOUT_S + + assert self._process is not None and self._process.stdin is not None + try: + self._process.stdin.write( + b"--%s\r\nContent-Type: image/jpeg\r\nContent-Length: %d\r\n\r\n" + % (self.BOUNDARY, len(data)) + + data + + b"\r\n" + ) + self._process.stdin.flush() + frame = self._frames.get(timeout=timeout) + except (OSError, queue.Empty) as e: + self.close() + raise RuntimeError(f"{self.name} pipeline did not return a frame") from e + + if frame is None: + self.close() + raise RuntimeError(f"{self.name} pipeline exited") + return frame + + def close(self) -> None: + if self._process is None: + return + self._process.kill() + self._process.wait() + self._process = None + self._sizes = None + + def _build_command(self, out_width: int, out_height: int) -> list[str]: + boundary = self.BOUNDARY.decode() + pipeline = ( + f"fdsrc fd=0 ! multipartdemux single-stream=true boundary={boundary} ! " + f"image/jpeg ! {self._decoder} ! {self._converter} ! " + f"{self._raw_caps},width={out_width},height={out_height} ! " + f"{self._encoder} quality={self._quality} ! " + f"multipartmux boundary={boundary} ! fdsink fd=1 sync=false" + ) + # Quiet, since status messages would otherwise be printed into the frames + return ["gst-launch-1.0", "-q", *pipeline.split(" ")] + + def _start(self, out_width: int, out_height: int) -> None: + self.close() + + command = self._build_command(out_width, out_height) + logger.debug("Starting JPEG scaler: %s", " ".join(command)) + self._process = subprocess.Popen( + command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + # A fresh queue, so a frame left over from an old pipeline is never returned + self._frames = queue.Queue() + + assert self._process.stdout is not None and self._process.stderr is not None + threading.Thread( + target=self._read_frames, + args=(self._process.stdout, self._frames), + daemon=True, + ).start() + threading.Thread( + target=self._log_errors, args=(self._process.stderr,), daemon=True + ).start() + + def _read_frames(self, stdout: BinaryIO, frames: queue.Queue[bytes | None]) -> None: + try: + while True: + frame = self._read_part(stdout) + if frame is None: + break + frames.put(frame) + except (OSError, ValueError) as e: + logger.warning("Unable to read from %s pipeline: %s", self.name, e) + # Tells a waiting scale() that no more frames will come + frames.put(None) + + def _read_part(self, stdout: BinaryIO) -> bytes | None: + """Read one multipart part, or None when the pipeline closes""" + line = stdout.readline() + # Parts are separated by a blank line + while line in (b"\r\n", b"\n"): + line = stdout.readline() + if not line: + return None + if line.strip() != b"--" + self.BOUNDARY: + raise ValueError(f"Unexpected multipart boundary: {line!r}") + + length: int | None = None + while (line := stdout.readline().strip()) != b"": + name, _, value = line.partition(b":") + if name.strip().lower() == b"content-length": + length = int(value) + if length is None: + raise ValueError("Multipart part has no Content-Length") + + data = bytearray() + while len(data) < length: + chunk = stdout.read(length - len(data)) + if not chunk: + return None + data += chunk + return bytes(data) + + def _log_errors(self, stderr: BinaryIO) -> None: + for line in stderr: + logger.warning("%s: %s", self.name, line.decode(errors="replace").rstrip()) + + +@functools.cache +def _has_gstreamer_elements(elements: tuple[str, ...]) -> bool: + if not shutil.which("gst-inspect-1.0"): + return False + for element in elements: + try: + result = subprocess.run( + ["gst-inspect-1.0", element], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + ) + except (OSError, subprocess.TimeoutExpired): + return False + if result.returncode != 0: + return False + return True + + +class AutoJpegScaler: + """ + Uses the hardware codec when the platform has one, and falls back to + libjpeg-turbo if it is missing or fails. Frames are passed through at full + size if nothing can scale them + """ + + def __init__(self) -> None: + self._candidates = [self._create_jetson, self._create_turbo] + self._active: JpegScaler | None = None + self._next_backend() + + def scale(self, data: bytes, width: int, height: int, scale: int) -> bytes: + """ + Return the JPEG in data shrunk to 1/scale of width and height, at the + quality it was encoded at + """ + if scale == 1: + return data + if scale not in SUPPORTED_SCALES: + raise ValueError(f"Unsupported stream scale: {scale}") + + quality = estimate_quality(data) + while self._active is not None: + try: + return self._active.scale(data, width, height, scale, quality) + except Exception as e: + logger.warning("%s could not scale a frame: %s", self._active.name, e) + self._active.close() + self._next_backend() + return data + + def close(self) -> None: + if self._active is not None: + self._active.close() + + def _next_backend(self) -> None: + self._active = None + while self._candidates: + scaler = self._candidates.pop(0)() + if scaler is not None: + logger.info("Scaling streamed frames with JPEG codec: %s", scaler.name) + self._active = scaler + return + logger.error("No JPEG scaler is available, so frames are streamed full size") + + def _create_jetson(self) -> JpegScaler | None: + if not GStreamerJpegScaler.has_elements("nvjpegdec", "nvvidconv", "nvjpegenc"): + logger.info("No hardware JPEG codec found, falling back to software") + return None + return GStreamerJpegScaler.jetson() + + def _create_turbo(self) -> JpegScaler | None: + try: + return TurboJpegScaler() + except (ImportError, OSError, RuntimeError) as e: + logger.warning("libjpeg-turbo is unavailable: %s", e) + return None diff --git a/docker/Dockerfile b/docker/Dockerfile index 84c1fd16..e8a5a408 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -9,7 +9,7 @@ RUN apt-get update -y && apt-get install -y --no-install-recommends \ libgstreamer-plugins-base1.0-dev gstreamer1.0-tools \ gstreamer1.0-x gstreamer1.0-plugins-base gstreamer1.0-plugins-good \ gstreamer1.0-plugins-bad gstreamer1.0-libav gstreamer1.0-plugins-ugly \ - libimage-exiftool-perl \ + libimage-exiftool-perl libturbojpeg0 \ && apt-get clean && rm -rf /var/lib/apt/lists/* ARG TARGETARCH diff --git a/frontend/src/components/dwe/cameras/stream/stream.tsx b/frontend/src/components/dwe/cameras/stream/stream.tsx index 007d7f1b..670c0266 100644 --- a/frontend/src/components/dwe/cameras/stream/stream.tsx +++ b/frontend/src/components/dwe/cameras/stream/stream.tsx @@ -25,6 +25,19 @@ import { FollowerList } from "./follower-list"; import { CameraControls } from "../camera-controls"; import { toast } from "sonner"; +type StreamScale = components["schemas"]["StreamModel"]["stream_scale"]; + +// Fractions of the recorded resolution a synchronized recording can be streamed at +const STREAM_SCALES: Record = { + Full: 1, + "1/2": 2, + "1/4": 4, + "1/8": 8, +}; + +const streamScaleLabel = (scale: StreamScale) => + Object.keys(STREAM_SCALES).find((label) => STREAM_SCALES[label] === scale); + export const CameraStream = ({ bus_id }: { bus_id: string }) => { const device = useDeviceStore((state) => state.devices[bus_id]); const setUVCControl = useDeviceStore((state) => state.setUVCControl); @@ -171,6 +184,24 @@ export const CameraStream = ({ bus_id }: { bus_id: string }) => { )} + {/* The recording keeps full resolution, only the stream is scaled */} + {!isManaged && + isSynchronized && + device.stream.stream_type === "RECORDING" && ( + { + configureStream(bus_id, { + stream_scale: STREAM_SCALES[label], + }); + }} + /> + )} + {!isManaged && (