-
Notifications
You must be signed in to change notification settings - Fork 24
perf(csi): request YUV420 main stream when supported (-28% to -39% CPU) #147
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mryel00
merged 19 commits into
mainsail-crew:develop
from
antoinecellerier:csi-yuv420-stream
Jun 22, 2026
+229
−2
Merged
Changes from 5 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
ab49117
feat: lazy-start picamera2 encoders to save idle CPU
antoinecellerier 7ac9e50
feat: stop the picamera2 capture loop when no consumers
antoinecellerier 56cd5df
feat: add per-encoder linger to preserve the warm path for timelapse
antoinecellerier e83a40a
perf(csi): request YUV420 main stream when supported
antoinecellerier ec60937
refactor: improve code readability
mryel00 49dd8f3
refactor: adjust logging messages
mryel00 10e98ef
test: adjust test code
mryel00 f0ab95e
style: adjust code style
mryel00 6537122
style: remove unnecessary comments
mryel00 0ad5eb0
refactor: improve code readability
mryel00 e405d2c
fix: remove deprecated argument style for new options
mryel00 ea0ca4b
test(cli): remove unnecessary tests and fix tests
mryel00 d09444c
Merge branch 'develop' into lazy-encoders
mryel00 fe782dd
refactor: merge two early returns
mryel00 238bbb3
fix: fix typo in logging message
mryel00 0a26d79
refactor(lazy_encoder): remove unnecessary condition in release
mryel00 51c5794
refactor(lazy_encoder): improve release code quality
mryel00 318787a
Merge branch 'lazy-encoders' into csi-yuv420-stream
mryel00 3321750
Merge branch 'develop' into csi-yuv420-stream
mryel00 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| # 002 - Main Stream Pixel Format for CSI Cameras | ||
|
|
||
| ## Date | ||
|
|
||
| 2026-05-31 | ||
|
|
||
| ## Status | ||
|
|
||
| Decision | ||
|
|
||
| ## Category | ||
|
|
||
| Performance | ||
|
|
||
| ## Authors | ||
|
|
||
| @antoinecellerier | ||
|
|
||
| ## References | ||
|
|
||
| [picamera2 V4L2 encoder source](https://github.com/raspberrypi/picamera2/blob/main/picamera2/encoders/v4l2_encoder.py) | ||
|
|
||
| ## Context | ||
|
|
||
| `picamera2.create_video_configuration()` defaults the main stream to `XBGR8888` | ||
| (32 bits/pixel). Both the V4L2 hardware encoders (`MJPEGEncoder`, | ||
| `H264Encoder`) and the `JpegEncoder` software fallback accept `YUV420` | ||
| (12 bits/pixel) as a native input. Forcing `YUV420` upstream of the encoders | ||
| skips an implicit colour-space conversion and reduces DMA bandwidth by ~2.7×. | ||
|
|
||
| ## Options | ||
|
|
||
| 1. Keep the picamera2 default (`XBGR8888`). | ||
| 2. Request `YUV420` for the main stream, falling back to the picamera2 default | ||
| when the camera does not advertise it. | ||
|
|
||
| ## Decision | ||
|
|
||
| We request `YUV420` for the main stream when libcamera reports it as supported, | ||
| selected from a preference-ordered list of encoder-compatible formats with | ||
| `YUV420` first. If none are supported, we omit `format` from the config and | ||
| defer to the picamera2 default. | ||
|
|
||
| ## Consequences | ||
|
|
||
| * Measured CPU on a Pi 4B with Camera Module 3 at 1920×1080 @ 30 fps drops by | ||
| ~28–39 % (idle and live WebRTC respectively) versus the `XBGR8888` default. | ||
| * No expected image-quality impact: JPEG and H.264 both encode in YUV | ||
| internally, so this change moves the colour-space conversion earlier in the | ||
| pipeline rather than introducing a new one. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| import sys | ||
| from unittest.mock import MagicMock | ||
|
|
||
| AF_MODE_ENUM_MANUAL = 3 | ||
| AF_SPEED_ENUM_NORMAL = 1 | ||
|
|
||
| mock_libcamera = MagicMock() | ||
| mock_picamera2 = MagicMock() | ||
| mock_picamera2.encoders._hw_encoder_available = False | ||
| mock_picamera2.outputs.Output = MagicMock | ||
| sys.modules.update( | ||
| { | ||
| "libcamera": mock_libcamera, | ||
| "picamera2": mock_picamera2, | ||
| "picamera2.encoders": mock_picamera2.encoders, | ||
| "picamera2.outputs": mock_picamera2.outputs, | ||
| } | ||
| ) | ||
| mock_libcamera.controls.AfModeEnum.Manual = AF_MODE_ENUM_MANUAL | ||
| mock_libcamera.controls.AfSpeedEnum.Normal = AF_SPEED_ENUM_NORMAL | ||
| mock_libcamera.StreamRole.VideoRecording = object() | ||
|
|
||
|
|
||
| def _make_picam2(supported_formats=[], enumerate_raises=None): | ||
| """Build a mocked Picamera2 whose libcamera-level | ||
| ``camera.generate_configuration(...)`` reports the given pixel formats.""" | ||
| picam2 = MagicMock() | ||
| picam2.camera_controls = {} | ||
| picam2.create_video_configuration.side_effect = lambda **kw: dict(kw) | ||
|
|
||
| if enumerate_raises is not None: | ||
| picam2.camera.generate_configuration.side_effect = enumerate_raises | ||
| else: | ||
| formats = MagicMock() | ||
| formats.pixel_formats = supported_formats | ||
| stream_cfg = MagicMock() | ||
| stream_cfg.formats = formats | ||
| libcam_cfg = MagicMock() | ||
| libcam_cfg.at.return_value = stream_cfg | ||
| picam2.camera.generate_configuration.return_value = libcam_cfg | ||
| return picam2 | ||
|
|
||
|
|
||
| def _run_configure(cam): | ||
| cam.configure( | ||
| width=1920, | ||
| height=1080, | ||
| fps=30, | ||
| autofocus=AF_MODE_ENUM_MANUAL, | ||
| lens_position=0.0, | ||
| autofocus_speed=AF_SPEED_ENUM_NORMAL, | ||
| ) | ||
|
|
||
|
|
||
| def test_csi_picks_yuv420_when_supported(): | ||
| from spyglass.camera.csi import CSI | ||
|
|
||
| picam2 = _make_picam2( | ||
| supported_formats=["YUV420", "XBGR8888", "BGR888", "NV12", "RGB565"] | ||
| ) | ||
| cam = CSI(picam2) | ||
| _run_configure(cam) | ||
|
|
||
| main = picam2.create_video_configuration.call_args.kwargs["main"] | ||
| assert main == {"size": (1920, 1080), "format": "YUV420"} | ||
|
|
||
|
|
||
| def test_csi_falls_through_preference_when_yuv420_missing(): | ||
| from spyglass.camera.csi import CSI | ||
|
|
||
| picam2 = _make_picam2(supported_formats=["XBGR8888", "BGR888", "RGB565"]) | ||
| cam = CSI(picam2) | ||
| _run_configure(cam) | ||
|
|
||
| main = picam2.create_video_configuration.call_args.kwargs["main"] | ||
| assert main == {"size": (1920, 1080), "format": "BGR888"} | ||
|
|
||
|
|
||
| def test_csi_omits_format_when_no_encoder_compatible_supported(): | ||
| from spyglass.camera.csi import CSI | ||
|
|
||
| picam2 = _make_picam2(supported_formats=["NV12", "NV21", "RGB565", "YUYV"]) | ||
| cam = CSI(picam2) | ||
| _run_configure(cam) | ||
|
|
||
| main = picam2.create_video_configuration.call_args.kwargs["main"] | ||
| assert "format" not in main | ||
| assert main == {"size": (1920, 1080)} | ||
|
|
||
|
|
||
| def test_csi_omits_format_when_enumeration_fails(): | ||
| from spyglass.camera.csi import CSI | ||
|
|
||
| picam2 = _make_picam2(enumerate_raises=RuntimeError("camera not yet acquired")) | ||
| cam = CSI(picam2) | ||
| _run_configure(cam) | ||
|
|
||
| main = picam2.create_video_configuration.call_args.kwargs["main"] | ||
| assert "format" not in main | ||
|
|
||
|
|
||
| def test_base_camera_does_not_query_libcamera_formats(): | ||
| """Subclasses other than CSI (e.g. USB) should not auto-pick a format.""" | ||
| from spyglass.camera.camera import Camera | ||
|
|
||
| class _StubCamera(Camera): | ||
| def start_and_run_server(self, *args, **kwargs): | ||
| raise NotImplementedError | ||
|
|
||
| def stop(self): | ||
| raise NotImplementedError | ||
|
|
||
| picam2 = _make_picam2(supported_formats=["YUV420"]) | ||
| cam = _StubCamera(picam2) | ||
| _run_configure(cam) | ||
|
|
||
| picam2.camera.generate_configuration.assert_not_called() | ||
| main = picam2.create_video_configuration.call_args.kwargs["main"] | ||
| assert "format" not in main |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.