camera_fanout.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. """MJPEG fan-out broadcaster for camera streams.
  2. Most Bambu Lab printers only allow one concurrent camera connection: the
  3. RTSP socket on X1/H2/P2 models, the chamber-image socket on port 6000 on
  4. A1/P1 models. Without fan-out, opening a second viewer either fails or
  5. kicks the first viewer off — see issue #1089.
  6. This module owns a single upstream connection per printer and pushes each
  7. frame to N independent subscriber queues. New viewers tap the existing
  8. upstream; no new printer connection is opened. When the last subscriber
  9. leaves, the upstream is torn down after a short grace window so that a
  10. quick page refresh or second-tab open does not pay a reconnect.
  11. """
  12. from __future__ import annotations
  13. import asyncio
  14. import logging
  15. from collections.abc import AsyncGenerator, Awaitable, Callable
  16. logger = logging.getLogger(__name__)
  17. # How long to keep the upstream pump alive after the last subscriber leaves.
  18. # A short grace window absorbs page refreshes and "open camera in new tab"
  19. # without paying a fresh ffmpeg/RTSP handshake (which can take several seconds
  20. # on some firmwares and is the very reconnect cost we are trying to avoid).
  21. _GRACE_SECONDS = 5.0
  22. # Upper bound on how long a new broadcaster waits for a displaced one to finish
  23. # tearing down before proceeding anyway (#2521). Teardown is normally sub-second
  24. # (cancel pump + close socket); the cap only guards a wedged upstream close.
  25. _TEARDOWN_WAIT_SECONDS = 10.0
  26. # Per-subscriber queue depth. Small on purpose: if a viewer can't keep up
  27. # with the printer's frame rate we drop frames for that viewer rather than
  28. # blocking the broadcaster. Live video — old frames have no value.
  29. _SUBSCRIBER_QUEUE_SIZE = 4
  30. # Sentinel pushed to subscriber queues when the upstream pump exits, so each
  31. # subscriber's read loop can break out cleanly instead of hanging on get().
  32. _UPSTREAM_GONE = b""
  33. # How often a subscriber that isn't receiving frames re-checks whether its
  34. # client is still connected. Only pays a cost when the stream is *not* producing
  35. # frames — the normal path returns from queue.get() as soon as a frame lands and
  36. # checks after the yield. Kept short because the subscriber count derived from
  37. # it is what /camera/stop uses to decide whether to tear the upstream down.
  38. _DISCONNECT_POLL_SECONDS = 1.0
  39. UpstreamFactory = Callable[[asyncio.Event], AsyncGenerator[bytes, None]]
  40. class MjpegBroadcaster:
  41. """Single upstream MJPEG stream, fanned out to N subscribers."""
  42. def __init__(self, key: str, factory: UpstreamFactory, predecessor: MjpegBroadcaster | None = None) -> None:
  43. self._key = key
  44. self._factory = factory
  45. self._subscribers: list[asyncio.Queue[bytes]] = []
  46. self._lock = asyncio.Lock()
  47. self._pump_task: asyncio.Task | None = None
  48. self._grace_task: asyncio.Task | None = None
  49. # Disconnect event passed to the upstream generator so we can ask it to
  50. # stop reconnecting when the last subscriber leaves.
  51. self._upstream_disconnect = asyncio.Event()
  52. self._stopped = False
  53. # Most recent chunk pumped to subscribers. New (late) subscribers are
  54. # primed with it so the browser renders a frame immediately instead of
  55. # waiting for the next upstream frame — critical on slow chamber-image
  56. # cams where the wait looked like a permanent black screen (#2521).
  57. self._last_chunk: bytes | None = None
  58. # Set once teardown is fully complete (pump cancelled AND the upstream
  59. # socket closed). A successor broadcaster waits on this before dialing
  60. # so a single-connection printer never sees two sockets at once — the
  61. # overlap stranded frames on an orphaned socket for the ~20 min it took
  62. # the printer's TCP keepalive to reap it (#2521).
  63. self._teardown_complete = asyncio.Event()
  64. # The stopped broadcaster this one replaces, if any. The pump waits for
  65. # its socket to close before opening ours. Guarding at the pump (not at
  66. # get_or_create) keeps it correct when concurrent viewers race to
  67. # replace the same stopped broadcaster — only the single pump dials.
  68. self._predecessor = predecessor
  69. @property
  70. def key(self) -> str:
  71. return self._key
  72. @property
  73. def subscriber_count(self) -> int:
  74. return len(self._subscribers)
  75. @property
  76. def stopped(self) -> bool:
  77. return self._stopped
  78. async def subscribe(self) -> asyncio.Queue[bytes]:
  79. """Add a subscriber and ensure the upstream pump is running."""
  80. async with self._lock:
  81. if self._stopped:
  82. raise RuntimeError(f"broadcaster {self._key!r} is stopped")
  83. # Cancel any pending grace-window shutdown — a viewer just rejoined.
  84. if self._grace_task is not None and not self._grace_task.done():
  85. self._grace_task.cancel()
  86. self._grace_task = None
  87. queue: asyncio.Queue[bytes] = asyncio.Queue(maxsize=_SUBSCRIBER_QUEUE_SIZE)
  88. self._subscribers.append(queue)
  89. # Prime a late joiner with the last frame so it renders instantly
  90. # (#2521). The very first subscriber has nothing to prime yet — it
  91. # starts the pump below.
  92. if self._last_chunk is not None:
  93. try:
  94. queue.put_nowait(self._last_chunk)
  95. except asyncio.QueueFull: # pragma: no cover — fresh queue
  96. pass
  97. if self._pump_task is None or self._pump_task.done():
  98. # Reset the disconnect signal in case a previous pump set it.
  99. self._upstream_disconnect = asyncio.Event()
  100. self._pump_task = asyncio.create_task(self._pump(), name=f"camera-fanout-pump-{self._key}")
  101. return queue
  102. async def unsubscribe(self, queue: asyncio.Queue[bytes]) -> int:
  103. """Remove a subscriber and return the remaining count (atomic).
  104. If this was the last subscriber, schedule grace shutdown.
  105. """
  106. async with self._lock:
  107. try:
  108. self._subscribers.remove(queue)
  109. except ValueError:
  110. return len(self._subscribers) # Already removed (e.g. force_shutdown)
  111. remaining = len(self._subscribers)
  112. if remaining == 0 and not self._stopped:
  113. # Last subscriber left. Schedule grace-window teardown.
  114. self._grace_task = asyncio.create_task(self._grace_then_stop(), name=f"camera-fanout-grace-{self._key}")
  115. return remaining
  116. async def force_shutdown(self) -> None:
  117. """Tear down immediately, kick all subscribers. Idempotent."""
  118. pump_task = await self._mark_stopped_locked(notify_subscribers=True)
  119. await self._await_pump_cancellation(pump_task)
  120. # Upstream socket is now closed (pump's finally ran) — release anyone
  121. # waiting to open a replacement broadcaster (#2521).
  122. self._teardown_complete.set()
  123. async def wait_until_torn_down(self) -> None:
  124. """Block until this broadcaster's upstream socket has fully closed.
  125. Only meaningful for a stopped broadcaster; on a live one this never
  126. returns. get_or_create_broadcaster gates a replacement on it so the
  127. old and new upstream sockets never overlap (#2521).
  128. """
  129. await self._teardown_complete.wait()
  130. async def _grace_then_stop(self) -> None:
  131. try:
  132. await asyncio.sleep(_GRACE_SECONDS)
  133. except asyncio.CancelledError:
  134. return # New subscriber arrived during grace
  135. # Re-check under the lock — a subscriber may have rejoined between
  136. # the sleep finishing and us acquiring the lock.
  137. pump_task: asyncio.Task | None = None
  138. async with self._lock:
  139. if self._subscribers or self._stopped:
  140. return
  141. self._upstream_disconnect.set()
  142. pump_task = self._pump_task
  143. self._pump_task = None
  144. self._grace_task = None
  145. self._stopped = True
  146. await self._await_pump_cancellation(pump_task)
  147. # Upstream socket is now closed — release any pending replacement (#2521).
  148. self._teardown_complete.set()
  149. async def _mark_stopped_locked(self, *, notify_subscribers: bool) -> asyncio.Task | None:
  150. """Mark the broadcaster stopped and detach the pump task.
  151. Caller MUST NOT hold ``self._lock`` (we acquire it here). Returns the
  152. pump task (if any) so the caller can await its cancellation OUTSIDE
  153. the lock — the pump's ``finally`` block needs the lock to wake up
  154. subscribers, so we'd deadlock if we awaited it under the lock.
  155. """
  156. async with self._lock:
  157. if self._stopped and self._pump_task is None:
  158. return None
  159. self._upstream_disconnect.set()
  160. if notify_subscribers:
  161. for queue in self._subscribers:
  162. try:
  163. queue.put_nowait(_UPSTREAM_GONE)
  164. except asyncio.QueueFull:
  165. pass
  166. self._subscribers.clear()
  167. pump_task = self._pump_task
  168. self._pump_task = None
  169. self._stopped = True
  170. if self._grace_task is not None and not self._grace_task.done():
  171. self._grace_task.cancel()
  172. self._grace_task = None
  173. return pump_task
  174. async def _await_pump_cancellation(self, pump_task: asyncio.Task | None) -> None:
  175. if pump_task is None or pump_task.done():
  176. return
  177. pump_task.cancel()
  178. try:
  179. await pump_task
  180. except (asyncio.CancelledError, Exception):
  181. # Pump exceptions are already logged inside _pump; swallow here so
  182. # teardown can never propagate a stray crash.
  183. pass
  184. async def _pump(self) -> None:
  185. """Drive the upstream generator and broadcast each chunk."""
  186. try:
  187. # Don't dial the printer until the broadcaster we're replacing has
  188. # closed its socket (#2521). Bounded so a wedged teardown degrades
  189. # to the old overlap behaviour rather than never producing a frame.
  190. predecessor = self._predecessor
  191. self._predecessor = None
  192. if predecessor is not None:
  193. try:
  194. await asyncio.wait_for(predecessor.wait_until_torn_down(), timeout=_TEARDOWN_WAIT_SECONDS)
  195. except asyncio.TimeoutError:
  196. logger.warning("Prior broadcaster %r didn't tear down in time; dialing anyway", self._key)
  197. async for chunk in self._factory(self._upstream_disconnect):
  198. # Snapshot subscribers under lock so we don't iterate a list
  199. # mutated by subscribe()/unsubscribe() while we are putting.
  200. # Remember the frame under the same lock so subscribe() can
  201. # prime a late joiner with a consistent last-chunk value (#2521).
  202. async with self._lock:
  203. self._last_chunk = chunk
  204. targets = list(self._subscribers)
  205. for queue in targets:
  206. try:
  207. queue.put_nowait(chunk)
  208. except asyncio.QueueFull:
  209. # Slow viewer — drop this frame for them. They'll catch
  210. # up on the next frame. Don't unsubscribe: a brief
  211. # browser stall shouldn't end the stream.
  212. pass
  213. except asyncio.CancelledError:
  214. raise
  215. except Exception:
  216. logger.exception("Camera fan-out pump crashed for %s", self._key)
  217. finally:
  218. # Pump is exiting — wake up any subscribers still hanging on get().
  219. async with self._lock:
  220. for queue in self._subscribers:
  221. try:
  222. queue.put_nowait(_UPSTREAM_GONE)
  223. except asyncio.QueueFull:
  224. pass
  225. # Global registry. Keyed by printer_id (as str) so a chamber-mode printer
  226. # and an RTSP-mode printer can never collide on the same key.
  227. _broadcasters: dict[str, MjpegBroadcaster] = {}
  228. _registry_lock = asyncio.Lock()
  229. async def get_or_create_broadcaster(key: str, factory: UpstreamFactory) -> MjpegBroadcaster:
  230. """Return the live broadcaster for `key`, creating one if needed.
  231. A broadcaster that has been stopped (force shutdown or grace timeout) is
  232. replaced with a fresh instance — the caller will subscribe to the new one.
  233. When replacing a stopped broadcaster, the fresh instance is handed it as a
  234. predecessor: its pump waits for the old socket to close before dialing, so
  235. a single-connection cam (chamber-image port 6000) never sees two sockets at
  236. once. Otherwise the printer keeps feeding the orphaned socket and starves
  237. the new one until its TCP keepalive reaps it, ~20 min later (#2521).
  238. """
  239. async with _registry_lock:
  240. existing = _broadcasters.get(key)
  241. if existing is not None and not existing.stopped:
  242. return existing
  243. # `existing` (if any) is stopped/tearing down — chain the new pump
  244. # behind its socket close.
  245. new_bc = MjpegBroadcaster(key, factory, predecessor=existing)
  246. _broadcasters[key] = new_bc
  247. return new_bc
  248. async def shutdown_broadcaster(key: str) -> bool:
  249. """Force-shutdown the broadcaster for `key`. Returns True if one was running.
  250. The stopped broadcaster stays in the registry on purpose. It used to be
  251. popped *before* ``force_shutdown()`` was awaited, which vacated the slot
  252. while the upstream socket was still closing: a ``/camera/stream`` request
  253. landing in that window found nothing, minted a broadcaster with
  254. ``predecessor=None``, and dialled the printer immediately. That is exactly
  255. the two-sockets-at-once overlap the predecessor gate exists to prevent —
  256. the gate only engages when the stopped broadcaster is still *findable*, and
  257. popping it here bypassed the gate in the one case it was written for. A page
  258. reload fires ``/camera/stop`` and the new stream request concurrently, so a
  259. single-connection cam (chamber-image port 6000) ended up with an orphaned
  260. socket that the printer kept feeding, starving the live viewer until the
  261. printer's TCP keepalive reaped it ~20 min later (#2521).
  262. Leaving it in place is safe: ``get_or_create_broadcaster`` replaces a stopped
  263. entry (chaining the successor behind its teardown), ``get_subscriber_count``
  264. reports 0 for it, and ``active_broadcaster_keys`` filters it out. There is at
  265. most one entry per printer, and it is overwritten by the next viewer.
  266. """
  267. async with _registry_lock:
  268. bc = _broadcasters.get(key)
  269. if bc is None or bc.stopped:
  270. return False
  271. await bc.force_shutdown()
  272. return True
  273. async def shutdown_all_broadcasters() -> None:
  274. """Tear down every broadcaster (for app shutdown)."""
  275. async with _registry_lock:
  276. bcs = list(_broadcasters.values())
  277. _broadcasters.clear()
  278. await asyncio.gather(*(bc.force_shutdown() for bc in bcs), return_exceptions=True)
  279. def active_broadcaster_keys() -> list[str]:
  280. """Snapshot of keys with a live (non-stopped) broadcaster. For diagnostics."""
  281. return [k for k, bc in _broadcasters.items() if not bc.stopped]
  282. def get_subscriber_count(key: str) -> int:
  283. """Return the number of live subscribers attached to ``key``, or 0.
  284. Used by ``/camera/stop`` to decide whether to force-shutdown the broadcaster
  285. or defer to natural cleanup. Other viewers (cam-wall tile, embedded viewer,
  286. popup window) all subscribe to the same broadcaster, so a force-shutdown
  287. triggered by one leaving viewer would kill the others' streams.
  288. """
  289. bc = _broadcasters.get(key)
  290. if bc is None or bc.stopped:
  291. return 0
  292. return bc.subscriber_count
  293. # ---------------------------------------------------------------------------
  294. # AsyncGenerator helper — turns a subscriber queue into an async generator
  295. # that yields MJPEG chunks until the upstream signals it's gone.
  296. # ---------------------------------------------------------------------------
  297. async def iter_subscriber(
  298. broadcaster: MjpegBroadcaster,
  299. queue: asyncio.Queue[bytes],
  300. *,
  301. is_disconnected: Callable[[], Awaitable[bool]] | None = None,
  302. on_unsubscribe: Callable[[int], None] | None = None,
  303. ) -> AsyncGenerator[bytes, None]:
  304. """Yield chunks from a subscriber queue until upstream ends or client leaves.
  305. Always unsubscribes from the broadcaster on exit, even on cancellation.
  306. The optional ``on_unsubscribe`` callback receives the post-unsubscribe
  307. subscriber count — useful for accurate detach-log lines that don't race
  308. with concurrent unsubscribes.
  309. """
  310. try:
  311. while True:
  312. try:
  313. chunk = await asyncio.wait_for(queue.get(), timeout=_DISCONNECT_POLL_SECONDS)
  314. except asyncio.TimeoutError:
  315. # No frame this tick — is the client still there? This used to
  316. # wait 30 s before asking, and the disconnect check after a yield
  317. # only fires when frames are actually flowing. So a viewer that
  318. # went away while the stream was black stayed *counted* as a
  319. # subscriber for up to half a minute — and ``/camera/stop``
  320. # trusts that count to decide whether to tear the upstream down,
  321. # so a phantom subscriber could make it skip teardown entirely
  322. # (#2521). Poll often enough that the count means something.
  323. if is_disconnected is not None and await is_disconnected():
  324. break
  325. continue
  326. if chunk == _UPSTREAM_GONE:
  327. break
  328. yield chunk
  329. if is_disconnected is not None and await is_disconnected():
  330. break
  331. finally:
  332. remaining = await broadcaster.unsubscribe(queue)
  333. if on_unsubscribe is not None:
  334. try:
  335. on_unsubscribe(remaining)
  336. except Exception:
  337. logger.exception("on_unsubscribe callback raised")