-
Notifications
You must be signed in to change notification settings - Fork 24
feat: lazy-start picamera2 encoders and camera to save idle CPU #146
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 12 commits into
mainsail-crew:develop
from
antoinecellerier:lazy-encoders
Jun 22, 2026
Merged
Changes from 4 commits
Commits
Show all changes
12 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 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 0a26d79
refactor(lazy_encoder): remove unnecessary condition in release
mryel00 51c5794
refactor(lazy_encoder): improve release code quality
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
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
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,161 @@ | ||
| """Reference-counted lazy start/stop wrappers for picamera2. | ||
|
|
||
| CameraSession wraps Picamera2.start()/stop(): the camera only runs while | ||
| at least one consumer (encoder) holds a reference. | ||
|
|
||
| LazyEncoder wraps Picamera2.start_encoder()/stop_encoder(): the encoder | ||
| only runs while at least one consumer (HTTP stream / snapshot / WebRTC | ||
| peer connection) holds a reference. Each LazyEncoder also holds a | ||
| reference on the CameraSession while running, so the camera itself | ||
| turns off when no encoders are active. | ||
|
|
||
| LazyEncoder supports a ``linger_seconds`` parameter: | ||
|
|
||
| * ``< 0`` keeps the encoder running once started; subsequent releases that | ||
| drive the ref-count to zero do not stop it. Useful for the MJPEG path | ||
| when paired with a startup pre-warm so e.g. timelapse snapshots stay on | ||
| the warm path. | ||
| * ``0`` stops the encoder immediately when the last consumer releases. | ||
| * ``> 0`` schedules a delayed stop; a fresh acquire within the window | ||
| cancels the pending stop. Useful to bridge brief reconnects without | ||
| paying the cold-start cost on every reconnect. | ||
| """ | ||
|
|
||
| import threading | ||
|
|
||
|
|
||
| class CameraSession: | ||
| def __init__(self, picam2): | ||
| self._picam2 = picam2 | ||
| self._refs = 0 | ||
| self._lock = threading.Lock() | ||
|
|
||
| def acquire(self): | ||
| with self._lock: | ||
| self._refs += 1 | ||
| if self._refs == 1: | ||
| try: | ||
| self._picam2.start() | ||
| except Exception: | ||
| self._refs -= 1 | ||
| raise | ||
|
|
||
| def release(self): | ||
| with self._lock: | ||
| if self._refs == 0: | ||
| return | ||
| self._refs -= 1 | ||
| if self._refs == 0: | ||
| self._picam2.stop() | ||
|
|
||
|
|
||
| class LazyEncoder: | ||
| def __init__( | ||
| self, | ||
| picam2, | ||
| encoder_factory, | ||
| output, | ||
| session=None, | ||
| linger_seconds=0, | ||
| ): | ||
| """ | ||
| :param picam2: the Picamera2 instance to start/stop the encoder on. | ||
| :param encoder_factory: zero-arg callable returning a fresh Encoder. | ||
| :param output: the picamera2 Output to attach to the encoder. | ||
| :param session: optional CameraSession. If provided, the camera is | ||
| started/stopped together with the encoder so the camera only runs | ||
| when at least one encoder is active. | ||
| :param linger_seconds: behavior when the last consumer releases. ``0`` | ||
| stops immediately; ``>0`` schedules a stop that is cancelled if a | ||
| new consumer acquires within the window; ``<0`` keeps the encoder | ||
| running forever after the first start. | ||
| """ | ||
| self._picam2 = picam2 | ||
| self._encoder_factory = encoder_factory | ||
| self._output = output | ||
| self._session = session | ||
| self._linger_seconds = linger_seconds | ||
| self._encoder = None | ||
| self._refs = 0 | ||
| self._lock = threading.Lock() | ||
| self._stop_timer = None | ||
| # Incremented on every cancel/schedule so a stale timer callback that | ||
| # has already raced past Timer.cancel() can detect it was superseded. | ||
| self._stop_token = 0 | ||
|
|
||
| def acquire(self): | ||
| with self._lock: | ||
| # If a linger-stop is pending, cancel it: the encoder is still | ||
| # running and we just need to claim a fresh reference. | ||
| self._cancel_linger_locked() | ||
| self._refs += 1 | ||
| if self._encoder is None: | ||
| session_acquired = False | ||
| try: | ||
| if self._session is not None: | ||
| self._session.acquire() | ||
| session_acquired = True | ||
| self._encoder = self._encoder_factory() | ||
| self._picam2.start_encoder(self._encoder, self._output) | ||
| except Exception: | ||
| # Roll back so a future caller can retry. | ||
| self._refs -= 1 | ||
| self._encoder = None | ||
| if session_acquired and self._session is not None: | ||
| self._session.release() | ||
| raise | ||
|
|
||
| def release(self): | ||
| with self._lock: | ||
| if self._refs == 0: | ||
| return | ||
| self._refs -= 1 | ||
| if self._refs == 0 and self._encoder is not None: | ||
| if self._linger_seconds < 0: | ||
| return | ||
| if self._linger_seconds == 0: | ||
| self._stop_now_locked() | ||
| else: | ||
| self._schedule_linger_locked() | ||
|
|
||
| def _stop_now_locked(self): | ||
| encoder = self._encoder | ||
| self._encoder = None | ||
| try: | ||
| self._picam2.stop_encoder(encoder) | ||
| finally: | ||
| if self._session is not None: | ||
| self._session.release() | ||
|
|
||
| def _cancel_linger_locked(self): | ||
| if self._stop_timer is not None: | ||
| self._stop_timer.cancel() | ||
| self._stop_timer = None | ||
| # Invalidate any in-flight callback that already raced past cancel(). | ||
| self._stop_token += 1 | ||
|
|
||
| def _schedule_linger_locked(self): | ||
| self._stop_token += 1 | ||
| token = self._stop_token | ||
| timer = threading.Timer( | ||
| self._linger_seconds, self._linger_callback, args=(token,) | ||
| ) | ||
| timer.daemon = True | ||
| self._stop_timer = timer | ||
| timer.start() | ||
|
|
||
| def _linger_callback(self, token): | ||
| with self._lock: | ||
| if self._stop_token != token: | ||
| # Superseded by a cancel or a fresh schedule; bail out. | ||
| return | ||
| self._stop_timer = None | ||
| if self._refs == 0 and self._encoder is not None: | ||
| self._stop_now_locked() | ||
|
|
||
| def __enter__(self): | ||
| self.acquire() | ||
| return self | ||
|
|
||
| def __exit__(self, *exc): | ||
| self.release() | ||
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
Oops, something went wrong.
Oops, something went wrong.
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.