camera.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815
  1. """Camera streaming API endpoints for Bambu Lab printers."""
  2. import asyncio
  3. import logging
  4. import os
  5. import subprocess
  6. import sys
  7. import time
  8. import uuid
  9. from collections.abc import AsyncGenerator
  10. from fastapi import APIRouter, Depends, HTTPException, Request
  11. from fastapi.responses import Response, StreamingResponse
  12. from sqlalchemy import select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core import database
  15. from backend.app.core.auth import (
  16. RequireCameraStreamTokenIfAuthEnabled,
  17. RequirePermissionIfAuthEnabled,
  18. create_camera_stream_token,
  19. )
  20. from backend.app.core.database import get_db
  21. from backend.app.core.logging_filters import redact_url_credentials
  22. from backend.app.core.permissions import Permission
  23. from backend.app.models.printer import Printer
  24. from backend.app.models.user import User
  25. from backend.app.services.camera import (
  26. capture_camera_frame,
  27. create_tls_proxy,
  28. generate_chamber_image_stream,
  29. get_camera_port,
  30. get_ffmpeg_path,
  31. is_chamber_image_model,
  32. read_next_chamber_frame,
  33. rtsp_socket_timeout_flag,
  34. test_camera_connection,
  35. )
  36. from backend.app.services.camera_fanout import (
  37. MjpegBroadcaster,
  38. get_or_create_broadcaster,
  39. get_subscriber_count,
  40. iter_subscriber,
  41. shutdown_broadcaster,
  42. )
  43. from backend.app.services.camera_profiles import get_camera_profile
  44. logger = logging.getLogger(__name__)
  45. router = APIRouter(prefix="/printers", tags=["camera"])
  46. # Grace period for a SIGTERMed ffmpeg to shut down before we SIGKILL it. Only
  47. # reachable when ffmpeg genuinely ignores SIGTERM: _terminate_ffmpeg drains the
  48. # pipes first, and a drained ffmpeg exits in ~0.15s.
  49. _FFMPEG_TERM_TIMEOUT = 2.0
  50. # Upper bound on waiting for a SIGKILLed ffmpeg to be reaped (#2580).
  51. #
  52. # The original diagnosis — "a killed ffmpeg stuck in uninterruptible I/O on a
  53. # dead RTSP socket" — was wrong, and this bound was capping a deadlock of our
  54. # own making rather than waiting out a stuck process. A process that survives
  55. # SIGKILL would have to be in uninterruptible sleep (state D); the ffmpeg seen
  56. # doing this was in state S, and its returncode was already set to -9 while
  57. # wait() was still blocked. The real cause was undrained pipes (see
  58. # _terminate_ffmpeg), which made this timeout fire on *every* camera close.
  59. #
  60. # Kept as a backstop now that the cause is fixed: it should no longer be
  61. # reachable, and if it ever is, abandoning the wait is still safe because
  62. # cleanup_orphaned_streams' /proc scan reaps any Bambu ffmpeg not attached to
  63. # an active stream on its next pass.
  64. _FFMPEG_KILL_TIMEOUT = 2.0
  65. # Track active ffmpeg processes for cleanup
  66. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  67. # Track active chamber image connections for cleanup
  68. _active_chamber_streams: dict[str, tuple] = {}
  69. # Store last frame for each printer (for photo capture from active stream)
  70. _last_frames: dict[int, bytes] = {}
  71. # Track last frame timestamp for each printer (for stall detection)
  72. _last_frame_times: dict[int, float] = {}
  73. # Track stream start times for each printer
  74. _stream_start_times: dict[int, float] = {}
  75. # Track active external camera streams by printer ID
  76. _active_external_streams: set[int] = set()
  77. # Track ALL spawned ffmpeg PIDs (persists even if _active_streams entries are removed)
  78. # Maps PID -> spawn timestamp — used by cleanup to find truly orphaned OS processes
  79. _spawned_ffmpeg_pids: dict[int, float] = {}
  80. # Track disconnect events per stream_id — allows stop endpoint and cleanup
  81. # to signal generators to stop reconnecting instead of just killing the process
  82. _disconnect_events: dict[str, asyncio.Event] = {}
  83. # Track last frame time per stream_id (not just per printer_id) for stale detection
  84. _stream_last_frame_times: dict[str, float] = {}
  85. def get_buffered_frame(printer_id: int) -> bytes | None:
  86. """Get the last buffered frame for a printer from an active stream.
  87. Returns the JPEG frame data if available, or None if no active stream.
  88. """
  89. return _last_frames.get(printer_id)
  90. def is_stream_active(printer_id: int) -> bool:
  91. """Return True iff a fan-out camera stream is currently registered for this printer.
  92. Snapshot callers (Obico polling, manual /camera/snapshot) MUST NOT open a
  93. second concurrent RTSP/chamber-image socket while a viewer is attached:
  94. most Bambu firmwares allow only one camera connection, so the competing
  95. socket either kicks the live viewer off or gets refused itself, and the
  96. resulting reconnect storm tears down the fan-out broadcaster (see #1348).
  97. Callers should consult this BEFORE trying to open a fresh socket and skip
  98. the capture cycle when it returns True — even if try_get_active_buffered_frame
  99. returns None (the stream may be running but the first frame hasn't landed
  100. in the buffer yet, or the upstream is mid-reconnect).
  101. """
  102. return any(k.startswith(f"{printer_id}-") for k in _active_streams) or any(
  103. k.startswith(f"{printer_id}-") for k in _active_chamber_streams
  104. )
  105. def try_get_active_buffered_frame(printer_id: int) -> bytes | None:
  106. """Return a buffered frame iff a stream is currently running for this printer.
  107. Snapshot callers (Obico polling, manual /camera/snapshot) tap the fan-out
  108. broadcaster's running upstream instead of opening a second concurrent
  109. RTSP/chamber-image socket. Critical for printers that allow only one
  110. camera connection (e.g. X2D firmware 01.01.00.00; see #1271).
  111. Returns None when no broadcaster is active for this printer, so callers
  112. fall through to their existing fresh-socket path unchanged.
  113. NB: returning None does NOT mean "safe to open a fresh socket" — it also
  114. fires when the stream is registered but no frame has been buffered yet
  115. (startup race, mid-reconnect). Callers that must avoid competing sockets
  116. should consult is_stream_active() first; see #1348.
  117. """
  118. if not is_stream_active(printer_id):
  119. return None
  120. return _last_frames.get(printer_id)
  121. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  122. """Get printer by ID or raise 404."""
  123. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  124. printer = result.scalar_one_or_none()
  125. if not printer:
  126. raise HTTPException(status_code=404, detail="Printer not found")
  127. return printer
  128. async def generate_chamber_mjpeg_stream(
  129. ip_address: str,
  130. access_code: str,
  131. model: str | None,
  132. fps: int = 5,
  133. stream_id: str | None = None,
  134. disconnect_event: asyncio.Event | None = None,
  135. printer_id: int | None = None,
  136. ) -> AsyncGenerator[bytes, None]:
  137. """Generate MJPEG stream from A1/P1 printer using chamber image protocol.
  138. This connects to port 6000 and reads JPEG frames using the Bambu binary protocol.
  139. """
  140. logger.info("Starting chamber image stream for %s (stream_id=%s, model=%s)", ip_address, stream_id, model)
  141. # Register disconnect event so stop endpoint can signal us
  142. if stream_id and disconnect_event:
  143. _disconnect_events[stream_id] = disconnect_event
  144. connection = await generate_chamber_image_stream(ip_address, access_code, fps)
  145. if connection is None:
  146. logger.error("Failed to connect to chamber image stream for %s", ip_address)
  147. yield (
  148. b"--frame\r\n"
  149. b"Content-Type: text/plain\r\n\r\n"
  150. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  151. )
  152. return
  153. reader, writer = connection
  154. # Track active connection for cleanup
  155. if stream_id:
  156. _active_chamber_streams[stream_id] = (reader, writer)
  157. try:
  158. frame_interval = 1.0 / fps if fps > 0 else 0.2
  159. last_frame_time = 0.0
  160. while True:
  161. # Check if client disconnected
  162. if disconnect_event and disconnect_event.is_set():
  163. logger.info("Client disconnected, stopping chamber stream %s", stream_id)
  164. break
  165. # Read next frame
  166. frame = await read_next_chamber_frame(reader, timeout=30.0)
  167. if frame is None:
  168. logger.warning("Chamber image stream ended for %s", stream_id)
  169. break
  170. # Save frame to buffer for photo capture and track timestamp
  171. if printer_id is not None:
  172. _last_frames[printer_id] = frame
  173. _last_frame_times[printer_id] = time.time()
  174. # Rate limiting - skip frames if needed to maintain target FPS
  175. current_time = asyncio.get_event_loop().time()
  176. if current_time - last_frame_time < frame_interval:
  177. continue
  178. last_frame_time = current_time
  179. # Yield frame in MJPEG format
  180. yield (
  181. b"--frame\r\n"
  182. b"Content-Type: image/jpeg\r\n"
  183. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  184. b"\r\n" + frame + b"\r\n"
  185. )
  186. except asyncio.CancelledError:
  187. logger.info("Chamber image stream cancelled (stream_id=%s)", stream_id)
  188. except GeneratorExit:
  189. logger.info("Chamber image stream generator exit (stream_id=%s)", stream_id)
  190. except Exception as e:
  191. logger.exception("Chamber image stream error: %s", e)
  192. finally:
  193. # Remove from active streams and disconnect events
  194. if stream_id:
  195. _active_chamber_streams.pop(stream_id, None)
  196. _disconnect_events.pop(stream_id, None)
  197. _stream_last_frame_times.pop(stream_id, None)
  198. # Clean up frame buffer and timestamps
  199. _release_printer_frame_state(printer_id)
  200. # Close the connection
  201. try:
  202. writer.close()
  203. await writer.wait_closed()
  204. except OSError:
  205. pass # Connection already closed or broken; cleanup is best-effort
  206. logger.info("Chamber image stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  207. def _new_fanout_stream_id(printer_id: int) -> str:
  208. """Registry key for one fan-out stream INSTANCE, not for the printer.
  209. A plain ``f"{printer_id}-fanout"`` meant every successive stream for a
  210. printer shared one key, so a departing generator's cleanup removed the entry
  211. its successor had just registered. The external-camera path already carries a
  212. per-instance suffix for exactly this reason (#2675); this gives the fan-out
  213. path the same property.
  214. The ``f"{printer_id}-"`` prefix is load-bearing — ``is_stream_active``,
  215. ``stop_camera_stream`` and ``/camera/status`` all find a printer's streams by
  216. scanning for it — so the suffix goes on the end.
  217. """
  218. return f"{printer_id}-fanout-{uuid.uuid4().hex[:8]}"
  219. def _release_printer_frame_state(printer_id: int | None) -> None:
  220. """Drop a printer's buffered frame and timings — unless a stream still owns them.
  221. These three dicts are keyed by printer, not by stream, so a departing
  222. generator must not clear them while a newer stream for the same printer is
  223. running. That used to happen routinely: stream ids were per-printer, so a
  224. predecessor's cleanup wiped its successor's state, leaving
  225. ``is_stream_active()`` False with a viewer attached (which is exactly what
  226. the #1348 / #1271 guards read before deciding whether it is safe to open a
  227. second camera connection), the janitor free to reap the live ffmpeg as an
  228. orphan, and snapshots without a frame to reuse.
  229. Call this AFTER removing the departing stream's own key, so the check
  230. reports on other streams rather than on the caller.
  231. """
  232. if printer_id is None or is_stream_active(printer_id):
  233. return
  234. _last_frames.pop(printer_id, None)
  235. _last_frame_times.pop(printer_id, None)
  236. _stream_start_times.pop(printer_id, None)
  237. async def _drain_pipe(reader) -> None:
  238. """Read a subprocess pipe to EOF and discard, so it can never block.
  239. Best-effort by design: any read failure means we cannot drain further, and
  240. the caller is tearing the process down regardless.
  241. """
  242. if reader is None:
  243. return
  244. try:
  245. while await reader.read(65536):
  246. pass
  247. except asyncio.CancelledError:
  248. raise
  249. except Exception: # noqa: BLE001 — teardown must not fail on a dying pipe
  250. return
  251. async def _terminate_ffmpeg(process: asyncio.subprocess.Process, stream_id: str | None = None) -> None:
  252. """Terminate an ffmpeg process gracefully, then kill if needed.
  253. Drains stdout/stderr throughout, which is load-bearing rather than hygiene.
  254. ffmpeg is spawned with both as pipes, and every caller of this has already
  255. stopped reading stdout — so by the time we get here ffmpeg is typically
  256. blocked in write() on a full 64 KiB pipe. Two things then go wrong:
  257. * SIGTERM cannot be acted on. ffmpeg's handler only sets a flag that its
  258. main loop polls, and a loop blocked in write() never reaches the check,
  259. so the whole grace period is dead time.
  260. * SIGKILL does kill it, but wait() cannot observe that. asyncio resolves
  261. Process.wait()'s waiter through BaseSubprocessTransport._try_finish(),
  262. which requires every pipe transport to report disconnected; paused,
  263. unread pipes never reach EOF, so wait() blocks with returncode already
  264. set. That is what made the "did not exit within Ns of SIGKILL" error
  265. fire on every single camera close, and unbounded it was the 12-hour
  266. hang in #2580.
  267. Draining fixes both: SIGTERM becomes actionable and the exit observable.
  268. Measured on an H2D: 4.0s of dead time per close before, ~0.15s after —
  269. which matters because the printer allows exactly one camera connection,
  270. so every one of those seconds was a connection nobody could use.
  271. Discarding what we drain is deliberate. The stream loop already reads
  272. stderr on its error paths (_read_ffmpeg_stderr), and it does so before
  273. calling this, so nothing diagnostic is lost.
  274. """
  275. if process.returncode is not None:
  276. _spawned_ffmpeg_pids.pop(process.pid, None)
  277. return # Already dead
  278. drainers = [
  279. asyncio.create_task(_drain_pipe(process.stdout)),
  280. asyncio.create_task(_drain_pipe(process.stderr)),
  281. ]
  282. try:
  283. process.terminate()
  284. try:
  285. await asyncio.wait_for(process.wait(), timeout=_FFMPEG_TERM_TIMEOUT)
  286. except TimeoutError:
  287. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  288. process.kill()
  289. try:
  290. await asyncio.wait_for(process.wait(), timeout=_FFMPEG_KILL_TIMEOUT)
  291. except TimeoutError:
  292. # Do NOT keep waiting (#2580): the caller is the stream
  293. # generator, and blocking here pins the fan-out pump forever.
  294. # The orphan janitor reaps the process later. With the pipes
  295. # drained this should be unreachable — see _FFMPEG_KILL_TIMEOUT.
  296. logger.error(
  297. "ffmpeg did not exit within %.1fs of SIGKILL; abandoning wait (stream_id=%s)",
  298. _FFMPEG_KILL_TIMEOUT,
  299. stream_id,
  300. )
  301. except ProcessLookupError:
  302. pass # Already dead
  303. except OSError as e:
  304. logger.warning("Error terminating ffmpeg: %s", e)
  305. finally:
  306. for drainer in drainers:
  307. drainer.cancel()
  308. await asyncio.gather(*drainers, return_exceptions=True)
  309. _spawned_ffmpeg_pids.pop(process.pid, None)
  310. def _summarize_ffmpeg_stderr(text: str | None) -> str:
  311. """Strip ffmpeg's boilerplate banner and keep only actionable lines.
  312. ffmpeg prints ~20 lines of version/build/configuration/lib headers before
  313. any actual error message. Logging the full banner on every retry floods
  314. the log (hundreds of lines per failed stream). This filter drops the
  315. banner and caps output at the last 10 meaningful lines.
  316. Credentials are masked here rather than at each ``logger`` call because
  317. this is the one funnel every stderr log in this module passes through.
  318. ffmpeg echoes the RTSP input URL back in its ``Input #0`` line, which
  319. carries the printer access code.
  320. """
  321. if not text:
  322. return ""
  323. text = redact_url_credentials(text) or ""
  324. banner_prefixes = (
  325. "ffmpeg version ",
  326. " built with ",
  327. " configuration:",
  328. " libavutil ",
  329. " libavcodec ",
  330. " libavformat ",
  331. " libavdevice ",
  332. " libavfilter ",
  333. " libswscale ",
  334. " libswresample ",
  335. " libpostproc ",
  336. )
  337. meaningful = [ln for ln in text.splitlines() if ln.strip() and not ln.startswith(banner_prefixes)]
  338. return "\n".join(meaningful[-10:])
  339. async def _read_ffmpeg_stderr(process: asyncio.subprocess.Process) -> str | None:
  340. """Read whatever ffmpeg has written to stderr so far (best-effort).
  341. ffmpeg's stderr must be drained *incrementally*. A stalled-but-still-alive
  342. ffmpeg — the typical P2S RTSP failure, where it connects but never produces
  343. a frame — never closes stderr, so a plain ``stderr.read()`` (read-to-EOF)
  344. blocks until the wait_for timeout and returns nothing, discarding the
  345. banner + stream-analysis lines ffmpeg already printed. Reading in bounded
  346. chunks returns the buffered output promptly whether or not ffmpeg has
  347. exited. Returns the content with ffmpeg's boilerplate banner stripped.
  348. """
  349. if not process or not process.stderr:
  350. return None
  351. chunks: list[bytes] = []
  352. total = 0
  353. cap = 65536
  354. try:
  355. while total < cap:
  356. chunk = await asyncio.wait_for(process.stderr.read(8192), timeout=2.0)
  357. if not chunk:
  358. break # EOF — ffmpeg has exited
  359. chunks.append(chunk)
  360. total += len(chunk)
  361. except Exception:
  362. # Timed out waiting for more data — ffmpeg is alive but quiet now.
  363. # Fall through and return whatever it already printed.
  364. pass
  365. if not chunks:
  366. return None
  367. return _summarize_ffmpeg_stderr(b"".join(chunks).decode(errors="replace")) or None
  368. async def generate_rtsp_mjpeg_stream(
  369. ip_address: str,
  370. access_code: str,
  371. model: str | None,
  372. fps: int = 10,
  373. stream_id: str | None = None,
  374. disconnect_event: asyncio.Event | None = None,
  375. printer_id: int | None = None,
  376. ) -> AsyncGenerator[bytes, None]:
  377. """Generate MJPEG stream from printer camera using ffmpeg/RTSP.
  378. This is for X1/H2/P2 models that support RTSP streaming.
  379. Auto-reconnects when the printer drops the RTSP session (common on P2S).
  380. Per-model knobs (probesize, analyzeduration, reconnect cadence) come from
  381. :func:`camera_profiles.get_camera_profile` so quirky firmwares can be
  382. handled by adding a profile entry rather than tuning a global constant.
  383. """
  384. ffmpeg = get_ffmpeg_path()
  385. if not ffmpeg:
  386. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  387. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  388. return
  389. profile = get_camera_profile(model)
  390. port = get_camera_port(model)
  391. # Use a local TLS proxy so Python's OpenSSL handles TLS instead of
  392. # ffmpeg's GnuTLS. This fixes P2S (and potentially other models)
  393. # dropping the RTSP session after a few seconds due to GnuTLS's
  394. # hardened Debian defaults rejecting TLS renegotiation.
  395. proxy_port, proxy_server = await create_tls_proxy(ip_address, port)
  396. camera_url = f"rtsp://bblp:{access_code}@127.0.0.1:{proxy_port}/streaming/live/1"
  397. # ffmpeg command to output MJPEG stream to stdout
  398. cmd = [
  399. ffmpeg,
  400. "-rtsp_transport",
  401. "tcp",
  402. "-rtsp_flags",
  403. "prefer_tcp",
  404. # Socket I/O timeout name varies by ffmpeg version (#1504); see
  405. # rtsp_socket_timeout_flag(). The 30s value is microseconds for
  406. # both names.
  407. f"-{rtsp_socket_timeout_flag()}",
  408. "30000000",
  409. "-buffer_size",
  410. "1024000", # 1MB buffer
  411. "-max_delay",
  412. "500000", # 0.5 seconds max delay
  413. "-probesize",
  414. str(profile.probesize),
  415. "-analyzeduration",
  416. str(profile.analyzeduration),
  417. "-fflags",
  418. "nobuffer", # Reduce internal buffering
  419. "-flags",
  420. "low_delay", # Minimize decode latency
  421. *profile.extra_ffmpeg_input_args,
  422. "-i",
  423. camera_url,
  424. "-f",
  425. "mjpeg",
  426. "-q:v",
  427. "5",
  428. "-r",
  429. str(fps),
  430. "-an", # No audio
  431. "-", # Output to stdout
  432. ]
  433. # Register disconnect event so stop endpoint can signal us
  434. if stream_id and disconnect_event:
  435. _disconnect_events[stream_id] = disconnect_event
  436. logger.info(
  437. "Starting RTSP camera stream for %s (stream_id=%s, model=%s, fps=%s, probesize=%s, analyzeduration=%s)",
  438. ip_address,
  439. stream_id,
  440. model,
  441. fps,
  442. profile.probesize,
  443. profile.analyzeduration,
  444. )
  445. # Log the full argv so a support bundle shows the actual ffmpeg flags
  446. # (probesize, analyzeduration, transport, ...). Only camera_url carries a
  447. # secret (the access code), so redact just that one element.
  448. _redacted_cmd = ["rtsp://<redacted>/streaming/live/1" if a == camera_url else a for a in cmd]
  449. logger.debug("ffmpeg command: %s", " ".join(_redacted_cmd))
  450. # On Windows, spawn ffmpeg in its own process group so that
  451. # terminate() doesn't broadcast CTRL_C_EVENT to uvicorn (#605).
  452. spawn_kwargs: dict = {}
  453. if sys.platform == "win32":
  454. spawn_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
  455. jpeg_start = b"\xff\xd8"
  456. jpeg_end = b"\xff\xd9"
  457. reconnect_count = 0
  458. process = None
  459. got_any_frames = False
  460. try:
  461. while reconnect_count <= profile.rtsp_reconnect_max:
  462. # Check for client disconnect before (re)connecting
  463. if disconnect_event and disconnect_event.is_set():
  464. break
  465. if reconnect_count > 0:
  466. logger.info(
  467. "RTSP reconnecting (%d/%d) for %s (stream_id=%s)",
  468. reconnect_count,
  469. profile.rtsp_reconnect_max,
  470. ip_address,
  471. stream_id,
  472. )
  473. await asyncio.sleep(profile.rtsp_reconnect_delay)
  474. if disconnect_event and disconnect_event.is_set():
  475. break
  476. # Spawn ffmpeg
  477. process = await asyncio.create_subprocess_exec(
  478. *cmd,
  479. stdout=asyncio.subprocess.PIPE,
  480. stderr=asyncio.subprocess.PIPE,
  481. **spawn_kwargs,
  482. )
  483. if stream_id:
  484. _active_streams[stream_id] = process
  485. import time as _time
  486. _spawned_ffmpeg_pids[process.pid] = _time.time()
  487. # Brief check for immediate startup failures
  488. await asyncio.sleep(0.1)
  489. if process.returncode is not None:
  490. stderr = await process.stderr.read()
  491. stderr_text = _summarize_ffmpeg_stderr(stderr.decode(errors="replace"))
  492. logger.error("ffmpeg failed immediately (attempt %d): %s", reconnect_count + 1, stderr_text)
  493. _spawned_ffmpeg_pids.pop(process.pid, None)
  494. if not got_any_frames and reconnect_count == 0:
  495. # First attempt failed immediately — camera is likely unreachable
  496. yield (
  497. b"--frame\r\n"
  498. b"Content-Type: text/plain\r\n\r\n"
  499. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  500. )
  501. return
  502. reconnect_count += 1
  503. continue
  504. # Read JPEG frames from ffmpeg stdout
  505. buffer = b""
  506. stream_ended = False
  507. client_gone = False
  508. while True:
  509. if disconnect_event and disconnect_event.is_set():
  510. client_gone = True
  511. break
  512. try:
  513. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  514. if not chunk:
  515. # ffmpeg exited — log stderr and break to reconnect
  516. stderr_text = await _read_ffmpeg_stderr(process)
  517. if stderr_text:
  518. logger.warning("ffmpeg stderr (stream_id=%s): %s", stream_id, stderr_text)
  519. logger.warning("RTSP stream ended for %s (stream_id=%s), will reconnect", ip_address, stream_id)
  520. stream_ended = True
  521. break
  522. buffer += chunk
  523. # Extract complete JPEG frames from buffer
  524. while True:
  525. start_idx = buffer.find(jpeg_start)
  526. if start_idx == -1:
  527. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  528. break
  529. if start_idx > 0:
  530. buffer = buffer[start_idx:]
  531. end_idx = buffer.find(jpeg_end, 2)
  532. if end_idx == -1:
  533. break
  534. frame = buffer[: end_idx + 2]
  535. buffer = buffer[end_idx + 2 :]
  536. got_any_frames = True
  537. if printer_id is not None:
  538. _last_frames[printer_id] = frame
  539. _last_frame_times[printer_id] = time.time()
  540. if stream_id:
  541. _stream_last_frame_times[stream_id] = time.time()
  542. yield (
  543. b"--frame\r\n"
  544. b"Content-Type: image/jpeg\r\n"
  545. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  546. b"\r\n" + frame + b"\r\n"
  547. )
  548. except TimeoutError:
  549. stderr_text = await _read_ffmpeg_stderr(process)
  550. if stderr_text:
  551. logger.warning("ffmpeg stderr on timeout: %s", stderr_text)
  552. logger.warning("RTSP read timeout for %s (stream_id=%s)", ip_address, stream_id)
  553. stream_ended = True
  554. break
  555. except asyncio.CancelledError:
  556. logger.info("Camera stream cancelled (stream_id=%s)", stream_id)
  557. client_gone = True
  558. break
  559. except GeneratorExit:
  560. logger.info("Camera stream generator exit (stream_id=%s)", stream_id)
  561. client_gone = True
  562. break
  563. # Clean up this ffmpeg process before reconnecting or exiting
  564. await _terminate_ffmpeg(process, stream_id)
  565. process = None
  566. if client_gone:
  567. break
  568. # Check if stream was explicitly stopped (e.g., by stop endpoint)
  569. if stream_id and stream_id not in _active_streams:
  570. logger.info("Stream %s removed from active streams, stopping reconnect", stream_id)
  571. break
  572. if stream_ended:
  573. reconnect_count += 1
  574. continue
  575. # Normal exit (shouldn't reach here, but be safe)
  576. break
  577. if reconnect_count > profile.rtsp_reconnect_max:
  578. logger.error(
  579. "RTSP max reconnects (%d) reached for %s (stream_id=%s)",
  580. profile.rtsp_reconnect_max,
  581. ip_address,
  582. stream_id,
  583. )
  584. except FileNotFoundError:
  585. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  586. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  587. except asyncio.CancelledError:
  588. logger.info("Camera stream task cancelled (stream_id=%s)", stream_id)
  589. except GeneratorExit:
  590. logger.info("Camera stream generator closed (stream_id=%s)", stream_id)
  591. except Exception as e:
  592. logger.exception("Camera stream error: %s", e)
  593. finally:
  594. # Remove from active streams and disconnect events
  595. if stream_id:
  596. _active_streams.pop(stream_id, None)
  597. _disconnect_events.pop(stream_id, None)
  598. _stream_last_frame_times.pop(stream_id, None)
  599. # Clean up frame buffer and timestamps
  600. _release_printer_frame_state(printer_id)
  601. if process:
  602. await _terminate_ffmpeg(process, stream_id)
  603. logger.info("Camera stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  604. # Shut down the TLS proxy
  605. proxy_server.close()
  606. await proxy_server.wait_closed()
  607. @router.post("/camera/stream-token")
  608. async def create_stream_token(
  609. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  610. ):
  611. """Create a reusable token for camera stream/snapshot access.
  612. Returns a token valid for 60 minutes that can be appended as ?token=xxx
  613. to camera stream/snapshot URLs loaded via <img> tags.
  614. """
  615. return {"token": await create_camera_stream_token()}
  616. @router.get("/{printer_id}/camera/stream")
  617. async def camera_stream(
  618. printer_id: int,
  619. request: Request,
  620. fps: int = 10,
  621. _: None = RequireCameraStreamTokenIfAuthEnabled,
  622. ):
  623. """Stream live video from printer camera as MJPEG.
  624. This endpoint returns a multipart MJPEG stream that can be used directly
  625. in an <img> tag or video player.
  626. Requires a stream token query param (?token=xxx) when auth is enabled.
  627. Uses external camera if configured, otherwise uses built-in camera:
  628. - External: MJPEG, RTSP, or HTTP snapshot
  629. - A1/P1: Chamber image protocol (port 6000)
  630. - X1/H2/P2: RTSP via ffmpeg (port 322)
  631. Args:
  632. printer_id: Printer ID
  633. fps: Target frames per second (default: 10, max: 30)
  634. """
  635. # Fetch the printer in a short-lived session so the pooled DB connection is
  636. # released BEFORE we start streaming. A live MJPEG stream runs for as long
  637. # as the browser tab stays open (potentially hours); holding the
  638. # Depends(get_db) session across it pinned one pooled connection per open
  639. # camera tab per printer — a top contributor to pool exhaustion on large
  640. # farms (issue #2572). expire_on_commit=False keeps the printer's already-
  641. # loaded columns readable after the session closes, and everything below
  642. # reads only scalar attributes (model, ip_address, access_code,
  643. # external_camera_*) — no lazy loads.
  644. #
  645. # Reference async_session via the module (not a top-level import binding) so
  646. # the session maker is looked up at call time — that keeps it in sync with
  647. # reinitialize_database() and lets the test harness's patch of
  648. # backend.app.core.database.async_session take effect here.
  649. async with database.async_session() as db:
  650. printer = await get_printer_or_404(printer_id, db)
  651. # Check for external camera first
  652. if printer.external_camera_enabled and printer.external_camera_url:
  653. # NB: no `import time` / `import uuid` here, and don't reintroduce them.
  654. # A local import anywhere in this function makes the name function-local
  655. # for the WHOLE function, so the RTSP/chamber path below — which never
  656. # executes this branch — would raise UnboundLocalError on any printer
  657. # without an external camera. Both are imported at module level.
  658. from backend.app.services.external_camera import generate_mjpeg_stream
  659. # Limit external camera FPS to reduce browser load
  660. fps = min(max(fps, 1), 15)
  661. logger.info(
  662. "Using external camera (%s) for printer %s at %s fps", printer.external_camera_type, printer_id, fps
  663. )
  664. # Register the stream into the SAME registries the RTSP/chamber paths use
  665. # (#2675) so `/camera/stop` and cleanup_orphaned_streams can find and kill
  666. # a leaked ffmpeg holding a USB device open. Before this, external streams
  667. # only tracked _active_external_streams and were structurally invisible to
  668. # both the stop endpoint and the janitor. The stream_id keeps the
  669. # `{printer_id}-` prefix both scanners key on, plus a unique suffix so two
  670. # concurrent viewers of one printer don't clobber each other's entry.
  671. stream_id = f"{printer_id}-ext-{uuid.uuid4().hex[:8]}"
  672. stop_event = asyncio.Event()
  673. _disconnect_events[stream_id] = stop_event
  674. # Track stream start
  675. _stream_start_times[printer_id] = time.time()
  676. _active_external_streams.add(printer_id)
  677. # Mutable holder so the wrapper's finally can unregister whatever process
  678. # is currently registered (the RTSP path may respawn across reconnects).
  679. current_proc: dict[str, asyncio.subprocess.Process] = {}
  680. def _register_external_process(proc: asyncio.subprocess.Process) -> None:
  681. prev = current_proc.get("proc")
  682. if prev is not None and prev.pid != proc.pid:
  683. _spawned_ffmpeg_pids.pop(prev.pid, None)
  684. current_proc["proc"] = proc
  685. _active_streams[stream_id] = proc
  686. _spawned_ffmpeg_pids[proc.pid] = time.time()
  687. _stream_last_frame_times[stream_id] = time.time()
  688. async def external_stream_wrapper():
  689. """Wrap external stream to track start/stop and update frame times."""
  690. try:
  691. async for frame in generate_mjpeg_stream(
  692. printer.external_camera_url,
  693. printer.external_camera_type,
  694. fps,
  695. on_process=_register_external_process,
  696. stop_event=stop_event,
  697. ):
  698. # generate_mjpeg_stream already handles rate limiting;
  699. # track frame times (per-printer + per-stream) for stall detection
  700. now = time.time()
  701. _last_frame_times[printer_id] = now
  702. _stream_last_frame_times[stream_id] = now
  703. yield frame
  704. finally:
  705. # Best-effort unregister. If an abrupt disconnect skips this
  706. # finally, the registry entries persist — which is exactly what
  707. # lets the stop endpoint / janitor reap the leaked process.
  708. stop_event.set()
  709. proc = current_proc.get("proc")
  710. if proc is not None:
  711. _spawned_ffmpeg_pids.pop(proc.pid, None)
  712. _active_streams.pop(stream_id, None)
  713. _disconnect_events.pop(stream_id, None)
  714. _stream_last_frame_times.pop(stream_id, None)
  715. _active_external_streams.discard(printer_id)
  716. logger.info("External camera stream ended for printer %s", printer_id)
  717. return StreamingResponse(
  718. external_stream_wrapper(),
  719. media_type="multipart/x-mixed-replace; boundary=frame",
  720. headers={
  721. "Cache-Control": "no-cache, no-store, must-revalidate",
  722. "Pragma": "no-cache",
  723. "Expires": "0",
  724. },
  725. )
  726. # Validate FPS - A1/P1 models max out at ~5 FPS
  727. if is_chamber_image_model(printer.model):
  728. fps = min(max(fps, 1), 5)
  729. else:
  730. fps = min(max(fps, 1), 30)
  731. # Choose the appropriate stream generator based on model
  732. if is_chamber_image_model(printer.model):
  733. stream_generator = generate_chamber_mjpeg_stream
  734. logger.info("Using chamber image protocol for %s", printer.model)
  735. else:
  736. stream_generator = generate_rtsp_mjpeg_stream
  737. logger.info("Using RTSP protocol for %s", printer.model)
  738. # Track stream start time. Set only if absent so the value reflects when
  739. # the SHARED upstream first started streaming, not when each new viewer
  740. # attached — otherwise /camera/status would report stream_uptime jumping
  741. # backward whenever a second viewer joins. The upstream generator's
  742. # finally clears this entry when the upstream actually ends.
  743. _stream_start_times.setdefault(printer_id, time.time())
  744. # Fan-out broadcaster (#1089): one upstream connection per printer, shared
  745. # across all viewers. Most Bambu printers only allow a single concurrent
  746. # camera connection, so opening the same printer in two tabs would
  747. # otherwise kick the first viewer off. The broadcaster owns the single
  748. # upstream and the per-viewer disconnect handling.
  749. #
  750. # Note: the upstream's fps is fixed by the first viewer who creates the
  751. # broadcaster. Concurrent viewers share that rate; new viewers after
  752. # teardown create a fresh broadcaster at their requested fps.
  753. fanout_key = f"printer-{printer_id}"
  754. upstream_stream_id = _new_fanout_stream_id(printer_id)
  755. def _factory(disconnect_event: asyncio.Event):
  756. # Re-bind locals into the closure so the async generator below sees
  757. # them — disconnect_event is owned by the broadcaster and signalled
  758. # when the last subscriber leaves (after the grace window).
  759. return stream_generator(
  760. ip_address=printer.ip_address,
  761. access_code=printer.access_code,
  762. model=printer.model,
  763. fps=fps,
  764. stream_id=upstream_stream_id,
  765. disconnect_event=disconnect_event,
  766. printer_id=printer_id,
  767. )
  768. # Subscribe with a one-shot retry to close a tiny race: the grace-window
  769. # teardown can flip the broadcaster to `stopped=True` between the registry
  770. # lookup and our subscribe call. The retry forces the registry to mint a
  771. # fresh broadcaster (since the now-stopped one is replaced), and the second
  772. # subscribe is guaranteed to land on it before any teardown can fire.
  773. broadcaster: MjpegBroadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  774. try:
  775. queue = await broadcaster.subscribe()
  776. except RuntimeError:
  777. broadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  778. queue = await broadcaster.subscribe()
  779. logger.info(
  780. "Camera viewer attached to %s (subscribers=%d)",
  781. fanout_key,
  782. broadcaster.subscriber_count,
  783. )
  784. async def _is_disconnected() -> bool:
  785. try:
  786. return await request.is_disconnected()
  787. except Exception:
  788. # Older starlette/uvicorn can raise during teardown — treat that
  789. # as "client gone" so the subscriber cleanly unsubscribes.
  790. return True
  791. def _log_detach(remaining: int) -> None:
  792. logger.info("Camera viewer detached from %s (subscribers=%d)", fanout_key, remaining)
  793. async def _generate():
  794. async for chunk in iter_subscriber(
  795. broadcaster,
  796. queue,
  797. is_disconnected=_is_disconnected,
  798. on_unsubscribe=_log_detach,
  799. ):
  800. yield chunk
  801. return StreamingResponse(
  802. _generate(),
  803. media_type="multipart/x-mixed-replace; boundary=frame",
  804. headers={
  805. "Cache-Control": "no-cache, no-store, must-revalidate",
  806. "Pragma": "no-cache",
  807. "Expires": "0",
  808. },
  809. )
  810. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  811. async def stop_camera_stream(
  812. printer_id: int,
  813. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  814. ):
  815. """Stop active camera streams for a printer.
  816. Called by the frontend on viewer unmount (cam-wall tile, embedded viewer,
  817. popup window). Accepts both GET and POST (POST for sendBeacon compatibility).
  818. Reference-count guard: every viewer of a printer subscribes to the same
  819. fan-out broadcaster, so a force-shutdown triggered by ONE leaving viewer
  820. used to kill the others' streams (cam-wall tile froze when a user opened
  821. then closed the embedded viewer). If any subscriber is still attached,
  822. skip the force-teardown — the broadcaster's natural grace-shutdown (5 s
  823. after subscribers drop to 0) handles cleanup when the leaving viewer's
  824. HTTP connection actually closes.
  825. """
  826. broadcaster_key = f"printer-{printer_id}"
  827. remaining_subscribers = get_subscriber_count(broadcaster_key)
  828. if remaining_subscribers >= 1:
  829. logger.info(
  830. "Skipping force-shutdown for printer %s: %d subscriber(s) still attached; "
  831. "natural cleanup will tear down when last viewer disconnects",
  832. printer_id,
  833. remaining_subscribers,
  834. )
  835. return {"stopped": 0, "skipped": True}
  836. stopped = 0
  837. # Tear down the fan-out broadcaster first (#1089). This cleanly notifies
  838. # all subscribed viewers and asks the upstream generator to stop
  839. # reconnecting before we fall back to forcefully killing the process below.
  840. if await shutdown_broadcaster(broadcaster_key):
  841. logger.info("Shut down camera fan-out broadcaster for printer %s", printer_id)
  842. # Stop ffmpeg/RTSP streams
  843. to_remove = []
  844. for stream_id, process in list(_active_streams.items()):
  845. if stream_id.startswith(f"{printer_id}-"):
  846. to_remove.append(stream_id)
  847. # Signal the generator to stop reconnecting BEFORE killing the process
  848. event = _disconnect_events.get(stream_id)
  849. if event:
  850. event.set()
  851. if process.returncode is None:
  852. # Shared helper, not an inline copy: it bounds the post-kill
  853. # wait (#2580) — a killed-but-unreaped ffmpeg used to hang this
  854. # request forever, exactly when the user hit Stop to recover a
  855. # stuck stream.
  856. await _terminate_ffmpeg(process, stream_id)
  857. stopped += 1
  858. logger.info("Terminated ffmpeg process for stream %s", stream_id)
  859. _spawned_ffmpeg_pids.pop(process.pid, None)
  860. for stream_id in to_remove:
  861. _active_streams.pop(stream_id, None)
  862. _disconnect_events.pop(stream_id, None)
  863. _stream_last_frame_times.pop(stream_id, None)
  864. # Stop chamber image streams
  865. to_remove_chamber = []
  866. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  867. if stream_id.startswith(f"{printer_id}-"):
  868. to_remove_chamber.append(stream_id)
  869. # Signal the generator to stop
  870. event = _disconnect_events.get(stream_id)
  871. if event:
  872. event.set()
  873. try:
  874. writer.close()
  875. stopped += 1
  876. logger.info("Closed chamber image connection for stream %s", stream_id)
  877. except OSError as e:
  878. logger.warning("Error stopping chamber stream %s: %s", stream_id, e)
  879. for stream_id in to_remove_chamber:
  880. _active_chamber_streams.pop(stream_id, None)
  881. _disconnect_events.pop(stream_id, None)
  882. _stream_last_frame_times.pop(stream_id, None)
  883. logger.info("Stopped %s camera stream(s) for printer %s", stopped, printer_id)
  884. return {"stopped": stopped}
  885. @router.get("/{printer_id}/camera/snapshot")
  886. async def camera_snapshot(
  887. printer_id: int,
  888. _: None = RequireCameraStreamTokenIfAuthEnabled,
  889. ):
  890. """Capture a single frame from the printer camera.
  891. Returns a JPEG image.
  892. Requires a stream token query param (?token=xxx) when auth is enabled.
  893. """
  894. import tempfile
  895. from pathlib import Path
  896. # Fetch the printer in a short-lived session and release the pooled DB
  897. # connection BEFORE the camera capture below (up to 15s, longer under a
  898. # saturated FTP/camera pool). Holding a Depends(get_db) session across the
  899. # grab pinned one connection per snapshot — and the cam wall polls this
  900. # per tile every 8s — so overlapping captures could pile up connections on
  901. # a large farm (issue #2572, sibling of the camera_stream fix). Everything
  902. # below reads only already-loaded scalar columns (expire_on_commit=False).
  903. async with database.async_session() as db:
  904. printer = await get_printer_or_404(printer_id, db)
  905. # Check for external camera first
  906. if printer.external_camera_enabled and printer.external_camera_url:
  907. from backend.app.services.external_camera import capture_frame
  908. frame_data = await capture_frame(
  909. printer.external_camera_url,
  910. printer.external_camera_type,
  911. timeout=15,
  912. snapshot_url=printer.external_camera_snapshot_url,
  913. )
  914. if not frame_data:
  915. raise HTTPException(
  916. status_code=503,
  917. detail="Failed to capture frame from external camera.",
  918. )
  919. return Response(
  920. content=frame_data,
  921. media_type="image/jpeg",
  922. headers={
  923. "Cache-Control": "no-cache, no-store, must-revalidate",
  924. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  925. },
  926. )
  927. # Reuse the fan-out broadcaster's buffered frame when a viewer is already
  928. # watching — avoids opening a second concurrent RTSP socket on printers
  929. # that allow only one camera connection (e.g. X2D firmware 01.01.00.00;
  930. # see #1271). Buffered frame is <1s old while a viewer is connected.
  931. buffered = try_get_active_buffered_frame(printer_id)
  932. if buffered:
  933. return Response(
  934. content=buffered,
  935. media_type="image/jpeg",
  936. headers={
  937. "Cache-Control": "no-cache, no-store, must-revalidate",
  938. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  939. },
  940. )
  941. # Create temporary file for the snapshot (0600 so only the app user can read it)
  942. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  943. os.close(fd)
  944. temp_path = Path(tmp_name)
  945. temp_path.chmod(0o600)
  946. try:
  947. success = await capture_camera_frame(
  948. ip_address=printer.ip_address,
  949. access_code=printer.access_code,
  950. model=printer.model,
  951. output_path=temp_path,
  952. timeout=15,
  953. )
  954. if not success:
  955. raise HTTPException(
  956. status_code=503,
  957. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  958. )
  959. # Read and return the image
  960. with open(temp_path, "rb") as f:
  961. image_data = f.read()
  962. return Response(
  963. content=image_data,
  964. media_type="image/jpeg",
  965. headers={
  966. "Cache-Control": "no-cache, no-store, must-revalidate",
  967. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  968. },
  969. )
  970. finally:
  971. # Clean up temp file
  972. if temp_path.exists():
  973. temp_path.unlink()
  974. @router.get("/{printer_id}/camera/test")
  975. async def test_camera(
  976. printer_id: int,
  977. db: AsyncSession = Depends(get_db),
  978. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  979. ):
  980. """Test camera connection for a printer.
  981. Returns success status and any error message.
  982. """
  983. printer = await get_printer_or_404(printer_id, db)
  984. result = await test_camera_connection(
  985. ip_address=printer.ip_address,
  986. access_code=printer.access_code,
  987. model=printer.model,
  988. )
  989. return result
  990. @router.post("/{printer_id}/camera/diagnose")
  991. async def diagnose_camera_route(
  992. printer_id: int,
  993. db: AsyncSession = Depends(get_db),
  994. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  995. ):
  996. """Run staged diagnostics for a printer's camera path.
  997. Returns a structured result the frontend renders inline so users can
  998. self-diagnose "connection lost" before opening a ticket. See
  999. ``camera_diagnose`` for stage details and the live-stream shortcut.
  1000. """
  1001. import time
  1002. from backend.app.services.camera_diagnose import diagnose_camera
  1003. printer = await get_printer_or_404(printer_id, db)
  1004. # Look up live-stream evidence so the diagnostic can short-circuit
  1005. # instead of fighting a viewer for the printer's single camera slot.
  1006. has_live = is_stream_active(printer_id)
  1007. last_ts = _last_frame_times.get(printer_id) if has_live else None
  1008. live_age = (time.time() - last_ts) if (has_live and last_ts) else None
  1009. result = await diagnose_camera(
  1010. ip_address=printer.ip_address,
  1011. access_code=printer.access_code,
  1012. model=printer.model,
  1013. printer_id=printer_id,
  1014. has_live_stream=has_live,
  1015. live_frame_age_seconds=live_age,
  1016. )
  1017. return result.to_dict()
  1018. @router.get("/{printer_id}/camera/status")
  1019. async def camera_status(
  1020. printer_id: int,
  1021. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1022. ):
  1023. """Get the status of an active camera stream.
  1024. Returns whether a stream is active and when the last frame was received.
  1025. Used by the frontend to detect stalled streams and auto-reconnect.
  1026. """
  1027. import time
  1028. # Check if there's an active stream for this printer
  1029. has_active_stream = False
  1030. # Check external camera streams
  1031. if printer_id in _active_external_streams:
  1032. has_active_stream = True
  1033. # Check ffmpeg/RTSP streams
  1034. if not has_active_stream:
  1035. for stream_id in _active_streams:
  1036. if stream_id.startswith(f"{printer_id}-"):
  1037. process = _active_streams[stream_id]
  1038. if process.returncode is None:
  1039. has_active_stream = True
  1040. break
  1041. # Check chamber image streams
  1042. if not has_active_stream:
  1043. for stream_id in _active_chamber_streams:
  1044. if stream_id.startswith(f"{printer_id}-"):
  1045. has_active_stream = True
  1046. break
  1047. # Get timing information
  1048. current_time = time.time()
  1049. last_frame_time = _last_frame_times.get(printer_id)
  1050. stream_start_time = _stream_start_times.get(printer_id)
  1051. # Calculate seconds since last frame
  1052. seconds_since_frame = None
  1053. if last_frame_time is not None:
  1054. seconds_since_frame = current_time - last_frame_time
  1055. # Calculate stream uptime
  1056. stream_uptime = None
  1057. if stream_start_time is not None:
  1058. stream_uptime = current_time - stream_start_time
  1059. return {
  1060. "active": has_active_stream,
  1061. "has_frames": printer_id in _last_frames,
  1062. "seconds_since_frame": seconds_since_frame,
  1063. "stream_uptime": stream_uptime,
  1064. # Consider stalled if no frame for more than 10 seconds after stream started
  1065. "stalled": (
  1066. has_active_stream
  1067. and stream_uptime is not None
  1068. and stream_uptime > 5 # Give 5 seconds for stream to start
  1069. and (seconds_since_frame is None or seconds_since_frame > 10)
  1070. ),
  1071. }
  1072. @router.post("/{printer_id}/camera/external/test")
  1073. async def test_external_camera(
  1074. printer_id: int,
  1075. url: str,
  1076. camera_type: str,
  1077. db: AsyncSession = Depends(get_db),
  1078. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1079. ):
  1080. """Test external camera connection.
  1081. Args:
  1082. printer_id: Printer ID (for authorization)
  1083. url: Camera URL or USB device path to test
  1084. camera_type: Camera type ("mjpeg", "rtsp", "snapshot", "usb")
  1085. Returns:
  1086. Dict with {success: bool, error?: str, resolution?: str}
  1087. """
  1088. # Verify printer exists (for authorization)
  1089. await get_printer_or_404(printer_id, db)
  1090. from backend.app.services.external_camera import test_connection
  1091. return await test_connection(url, camera_type)
  1092. @router.get("/{printer_id}/camera/check-plate")
  1093. async def check_plate_empty(
  1094. printer_id: int,
  1095. plate_type: str | None = None,
  1096. use_external: bool | None = None,
  1097. include_debug_image: bool = False,
  1098. db: AsyncSession = Depends(get_db),
  1099. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1100. ):
  1101. """Check if the build plate is empty using camera vision.
  1102. Uses calibration-based difference detection - compares current frame
  1103. to a reference image of the empty plate.
  1104. IMPORTANT: Chamber light must be ON for reliable detection.
  1105. Args:
  1106. printer_id: Printer ID
  1107. plate_type: Type of build plate (e.g., "High Temp Plate") for calibration lookup
  1108. use_external: If True, prefer external camera over built-in. When omitted
  1109. (None), defaults to the printer's external_camera_enabled setting —
  1110. mirroring the runtime auto-check at print start (main.py). Without
  1111. this default the UI's manual check would always use the built-in
  1112. camera, mismatching the reference saved during calibration (#1359).
  1113. include_debug_image: If True, return URL to annotated debug image
  1114. Returns:
  1115. Dict with detection results:
  1116. - is_empty: bool - Whether plate appears empty
  1117. - confidence: float - Confidence level (0.0 to 1.0)
  1118. - difference_percent: float - How different from calibration reference
  1119. - message: str - Human-readable result message
  1120. - needs_calibration: bool - True if calibration is required
  1121. - light_warning: bool - True if chamber light is off
  1122. """
  1123. from backend.app.services.plate_detection import (
  1124. check_plate_empty as do_check,
  1125. is_plate_detection_available,
  1126. )
  1127. from backend.app.services.printer_manager import printer_manager
  1128. # Check printer exists first (before OpenCV check)
  1129. printer = await get_printer_or_404(printer_id, db)
  1130. if use_external is None:
  1131. use_external = bool(
  1132. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  1133. )
  1134. if not is_plate_detection_available():
  1135. raise HTTPException(
  1136. status_code=503,
  1137. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1138. )
  1139. # Check chamber light status
  1140. light_warning = False
  1141. state = printer_manager.get_status(printer_id)
  1142. if state and not state.chamber_light:
  1143. light_warning = True
  1144. from backend.app.services.plate_detection import PlateDetector
  1145. # Build ROI tuple from printer settings if available
  1146. roi = None
  1147. if all(
  1148. [
  1149. printer.plate_detection_roi_x is not None,
  1150. printer.plate_detection_roi_y is not None,
  1151. printer.plate_detection_roi_w is not None,
  1152. printer.plate_detection_roi_h is not None,
  1153. ]
  1154. ):
  1155. roi = (
  1156. printer.plate_detection_roi_x,
  1157. printer.plate_detection_roi_y,
  1158. printer.plate_detection_roi_w,
  1159. printer.plate_detection_roi_h,
  1160. )
  1161. result = await do_check(
  1162. printer_id=printer.id,
  1163. ip_address=printer.ip_address,
  1164. access_code=printer.access_code,
  1165. model=printer.model,
  1166. plate_type=plate_type,
  1167. include_debug_image=include_debug_image,
  1168. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1169. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1170. use_external=use_external,
  1171. roi=roi,
  1172. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1173. )
  1174. # Get reference count for the response
  1175. detector = PlateDetector()
  1176. ref_count = detector.get_calibration_count(printer.id)
  1177. response = result.to_dict()
  1178. response["light_warning"] = light_warning
  1179. response["reference_count"] = ref_count
  1180. response["max_references"] = detector.MAX_REFERENCES
  1181. # Include current ROI in response
  1182. if roi:
  1183. response["roi"] = {"x": roi[0], "y": roi[1], "w": roi[2], "h": roi[3]}
  1184. else:
  1185. # Return default ROI
  1186. response["roi"] = {"x": 0.15, "y": 0.35, "w": 0.70, "h": 0.55}
  1187. # If debug image requested and available, encode as base64 data URL
  1188. if include_debug_image and result.debug_image:
  1189. import base64
  1190. b64_image = base64.b64encode(result.debug_image).decode("utf-8")
  1191. response["debug_image_url"] = f"data:image/jpeg;base64,{b64_image}"
  1192. return response
  1193. @router.post("/{printer_id}/camera/plate-detection/calibrate")
  1194. async def calibrate_plate_detection(
  1195. printer_id: int,
  1196. label: str | None = None,
  1197. use_external: bool | None = None,
  1198. db: AsyncSession = Depends(get_db),
  1199. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1200. ):
  1201. """Calibrate plate detection by capturing a reference image of the empty plate.
  1202. The plate MUST be empty when calling this endpoint. The captured image
  1203. will be used as the reference for future detection comparisons.
  1204. Supports up to 5 reference images per printer. When adding a 6th, the oldest
  1205. is automatically removed.
  1206. IMPORTANT: Chamber light should be ON for calibration.
  1207. Args:
  1208. printer_id: Printer ID
  1209. label: Optional label for this reference (e.g., "High Temp Plate", "Wham Bam")
  1210. use_external: If True, prefer external camera over built-in. When omitted
  1211. (None), defaults to the printer's external_camera_enabled setting so
  1212. calibration captures from the same source the runtime auto-check
  1213. uses at print start (#1359).
  1214. Returns:
  1215. Dict with:
  1216. - success: bool - Whether calibration succeeded
  1217. - message: str - Status message
  1218. - index: int - The reference slot used (0-4)
  1219. """
  1220. from backend.app.services.plate_detection import (
  1221. calibrate_plate,
  1222. is_plate_detection_available,
  1223. )
  1224. from backend.app.services.printer_manager import printer_manager
  1225. # Check printer exists first (before OpenCV check)
  1226. printer = await get_printer_or_404(printer_id, db)
  1227. if use_external is None:
  1228. use_external = bool(
  1229. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  1230. )
  1231. if not is_plate_detection_available():
  1232. raise HTTPException(
  1233. status_code=503,
  1234. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1235. )
  1236. # Check chamber light - warn but don't block
  1237. state = printer_manager.get_status(printer_id)
  1238. light_warning = state and not state.chamber_light
  1239. success, message, index = await calibrate_plate(
  1240. printer_id=printer.id,
  1241. ip_address=printer.ip_address,
  1242. access_code=printer.access_code,
  1243. model=printer.model,
  1244. label=label,
  1245. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1246. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1247. use_external=use_external,
  1248. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1249. )
  1250. if light_warning and success:
  1251. message += " (Warning: Chamber light was off)"
  1252. return {"success": success, "message": message, "index": index}
  1253. @router.delete("/{printer_id}/camera/plate-detection/calibrate")
  1254. async def delete_plate_calibration(
  1255. printer_id: int,
  1256. plate_type: str | None = None,
  1257. db: AsyncSession = Depends(get_db),
  1258. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1259. ):
  1260. """Delete the plate detection calibration for a printer and plate type.
  1261. Args:
  1262. printer_id: Printer ID
  1263. plate_type: Type of build plate (if None, deletes legacy non-plate-specific calibration)
  1264. Returns:
  1265. Dict with:
  1266. - success: bool - Whether deletion succeeded
  1267. - message: str - Status message
  1268. """
  1269. from backend.app.services.plate_detection import (
  1270. delete_calibration,
  1271. is_plate_detection_available,
  1272. )
  1273. # Verify printer exists first (before OpenCV check)
  1274. await get_printer_or_404(printer_id, db)
  1275. if not is_plate_detection_available():
  1276. raise HTTPException(
  1277. status_code=503,
  1278. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1279. )
  1280. deleted = delete_calibration(printer_id, plate_type)
  1281. plate_msg = f" for '{plate_type}'" if plate_type else ""
  1282. return {
  1283. "success": deleted,
  1284. "message": f"Calibration deleted{plate_msg}" if deleted else f"No calibration found{plate_msg}",
  1285. }
  1286. @router.get("/{printer_id}/camera/plate-detection/status")
  1287. async def get_plate_detection_status(
  1288. printer_id: int,
  1289. plate_type: str | None = None,
  1290. db: AsyncSession = Depends(get_db),
  1291. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1292. ):
  1293. """Check plate detection status for a printer and plate type.
  1294. Returns:
  1295. Dict with:
  1296. - available: bool - Whether OpenCV is installed
  1297. - calibrated: bool - Whether printer has calibration for this plate type
  1298. - plate_type: str - The plate type queried
  1299. - chamber_light: bool - Whether chamber light is on
  1300. - message: str - Status message
  1301. """
  1302. from backend.app.services.plate_detection import (
  1303. get_calibration_status,
  1304. is_plate_detection_available,
  1305. )
  1306. from backend.app.services.printer_manager import printer_manager
  1307. # Verify printer exists first (before OpenCV check)
  1308. await get_printer_or_404(printer_id, db)
  1309. if not is_plate_detection_available():
  1310. return {
  1311. "available": False,
  1312. "calibrated": False,
  1313. "plate_type": plate_type,
  1314. "chamber_light": False,
  1315. "message": "OpenCV not installed",
  1316. }
  1317. # Get chamber light status
  1318. state = printer_manager.get_status(printer_id)
  1319. chamber_light = state.chamber_light if state else False
  1320. status = get_calibration_status(printer_id, plate_type)
  1321. status["chamber_light"] = chamber_light
  1322. return status
  1323. @router.get("/{printer_id}/camera/plate-detection/references")
  1324. async def get_plate_references(
  1325. printer_id: int,
  1326. db: AsyncSession = Depends(get_db),
  1327. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1328. ):
  1329. """Get all calibration references for a printer with metadata.
  1330. Returns list of references with index, label, timestamp, and thumbnail URL.
  1331. """
  1332. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1333. # Verify printer exists first (before OpenCV check)
  1334. await get_printer_or_404(printer_id, db)
  1335. if not is_plate_detection_available():
  1336. raise HTTPException(503, "Plate detection not available")
  1337. detector = PlateDetector()
  1338. references = detector.get_references(printer_id)
  1339. # Add thumbnail URLs
  1340. for ref in references:
  1341. ref["thumbnail_url"] = (
  1342. f"/api/v1/printers/{printer_id}/camera/plate-detection/references/{ref['index']}/thumbnail"
  1343. )
  1344. return {
  1345. "references": references,
  1346. "max_references": detector.MAX_REFERENCES,
  1347. }
  1348. @router.get("/{printer_id}/camera/plate-detection/references/{index}/thumbnail")
  1349. async def get_reference_thumbnail(
  1350. printer_id: int,
  1351. index: int,
  1352. db: AsyncSession = Depends(get_db),
  1353. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1354. ):
  1355. """Get thumbnail image for a calibration reference.
  1356. Requires a stream token query param (?token=xxx) when auth is enabled.
  1357. """
  1358. from fastapi.responses import Response
  1359. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1360. # Verify printer exists first (before OpenCV check)
  1361. await get_printer_or_404(printer_id, db)
  1362. if not is_plate_detection_available():
  1363. raise HTTPException(503, "Plate detection not available")
  1364. detector = PlateDetector()
  1365. thumbnail = detector.get_reference_thumbnail(printer_id, index)
  1366. if thumbnail is None:
  1367. raise HTTPException(404, "Reference not found")
  1368. return Response(content=thumbnail, media_type="image/jpeg")
  1369. @router.put("/{printer_id}/camera/plate-detection/references/{index}")
  1370. async def update_reference_label(
  1371. printer_id: int,
  1372. index: int,
  1373. label: str,
  1374. db: AsyncSession = Depends(get_db),
  1375. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1376. ):
  1377. """Update the label for a calibration reference."""
  1378. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1379. # Verify printer exists first (before OpenCV check)
  1380. await get_printer_or_404(printer_id, db)
  1381. if not is_plate_detection_available():
  1382. raise HTTPException(503, "Plate detection not available")
  1383. detector = PlateDetector()
  1384. success = detector.update_reference_label(printer_id, index, label)
  1385. if not success:
  1386. raise HTTPException(404, "Reference not found")
  1387. return {"success": True, "index": index, "label": label}
  1388. @router.delete("/{printer_id}/camera/plate-detection/references/{index}")
  1389. async def delete_reference(
  1390. printer_id: int,
  1391. index: int,
  1392. db: AsyncSession = Depends(get_db),
  1393. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1394. ):
  1395. """Delete a specific calibration reference."""
  1396. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1397. # Verify printer exists first (before OpenCV check)
  1398. await get_printer_or_404(printer_id, db)
  1399. if not is_plate_detection_available():
  1400. raise HTTPException(503, "Plate detection not available")
  1401. detector = PlateDetector()
  1402. success = detector.delete_reference(printer_id, index)
  1403. if not success:
  1404. raise HTTPException(404, "Reference not found")
  1405. return {"success": True, "message": "Reference deleted"}
  1406. def _scan_bambu_ffmpeg_pids() -> list[int]:
  1407. """Scan /proc for ffmpeg processes that are ours.
  1408. Two shapes are matched, both unambiguously Bambuddy's:
  1409. - Bambu RTSP: no other software connects to ``rtsp(s)://bblp:``.
  1410. - External USB (V4L2): an ffmpeg spawned with ``-f v4l2`` is our USB camera
  1411. stream (#2675). Only orphans are killed — the caller excludes PIDs still in
  1412. ``_active_streams``, so a live USB stream (now registered there) is spared.
  1413. This catches orphans that survive app restarts and are not in any tracking dict.
  1414. """
  1415. import os
  1416. pids = []
  1417. try:
  1418. for entry in os.listdir("/proc"):
  1419. if not entry.isdigit():
  1420. continue
  1421. try:
  1422. with open(f"/proc/{entry}/cmdline", "rb") as f:
  1423. cmdline = f.read()
  1424. if b"ffmpeg" not in cmdline:
  1425. continue
  1426. # Match both rtsp:// (via TLS proxy) and rtsps:// (direct), plus
  1427. # the `-f v4l2` input flag our USB camera command always carries.
  1428. if b"rtsp://bblp:" in cmdline or b"rtsps://bblp:" in cmdline or b"v4l2" in cmdline:
  1429. pids.append(int(entry))
  1430. except (OSError, PermissionError, ValueError):
  1431. continue
  1432. except OSError:
  1433. pass
  1434. return pids
  1435. async def cleanup_orphaned_streams():
  1436. """Clean up orphaned ffmpeg processes and stale stream entries.
  1437. Called periodically from the background task loop in main.py.
  1438. Three-layer cleanup:
  1439. 1. /proc scan — finds ALL Bambu ffmpeg processes on the system, even those
  1440. from previous app sessions. This is the nuclear safety net.
  1441. 2. _spawned_ffmpeg_pids — tracks PIDs spawned this session, catches orphans
  1442. that were removed from _active_streams but not killed.
  1443. 3. _active_streams — kills stale entries with no recent frames.
  1444. """
  1445. import os
  1446. import signal
  1447. import time
  1448. cleaned = 0
  1449. now = time.time()
  1450. # Collect PIDs that are legitimately in-use (active stream, process alive)
  1451. active_pids = {proc.pid for proc in _active_streams.values() if proc.returncode is None}
  1452. # Also exclude PIDs from one-shot snapshot captures (Obico detection, finish photos, etc.)
  1453. from backend.app.services.camera import _active_capture_pids
  1454. active_pids |= _active_capture_pids
  1455. # 1. /proc scan — catch ALL orphaned Bambu ffmpeg processes on the system.
  1456. # Any ffmpeg with rtsp(s)://bblp: that is NOT in an active stream is orphaned.
  1457. for pid in _scan_bambu_ffmpeg_pids():
  1458. if pid in active_pids:
  1459. continue
  1460. logger.info("Killing orphaned ffmpeg process found via /proc (pid=%d)", pid)
  1461. try:
  1462. os.kill(pid, signal.SIGKILL)
  1463. except (ProcessLookupError, OSError):
  1464. pass
  1465. _spawned_ffmpeg_pids.pop(pid, None)
  1466. cleaned += 1
  1467. # 2. Clean up _spawned_ffmpeg_pids entries for dead processes
  1468. for pid in list(_spawned_ffmpeg_pids):
  1469. try:
  1470. os.kill(pid, 0) # existence check
  1471. except (ProcessLookupError, OSError):
  1472. _spawned_ffmpeg_pids.pop(pid, None)
  1473. # 3. Clean up _active_streams entries with dead processes
  1474. dead_streams = [sid for sid, proc in _active_streams.items() if proc.returncode is not None]
  1475. for sid in dead_streams:
  1476. proc = _active_streams.pop(sid, None)
  1477. if proc:
  1478. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1479. cleaned += 1
  1480. # 4. Kill stale active streams (alive but no frames for >30s)
  1481. # Uses per-stream timestamps to avoid false "fresh" readings from newer streams
  1482. for sid, proc in list(_active_streams.items()):
  1483. if proc.returncode is not None:
  1484. continue
  1485. # Per-stream frame time is authoritative; fall back to per-printer
  1486. stream_last_frame = _stream_last_frame_times.get(sid)
  1487. if stream_last_frame is None:
  1488. try:
  1489. printer_id = int(sid.split("-", 1)[0])
  1490. except (ValueError, IndexError):
  1491. continue
  1492. stream_last_frame = _last_frame_times.get(printer_id)
  1493. spawn_time = _spawned_ffmpeg_pids.get(proc.pid, now)
  1494. if stream_last_frame is None:
  1495. stream_last_frame = spawn_time
  1496. if now - spawn_time > 60 and now - stream_last_frame > 30:
  1497. logger.info("Killing stale ffmpeg stream %s (no frames for %.0fs)", sid, now - stream_last_frame)
  1498. # Signal the generator to stop reconnecting
  1499. event = _disconnect_events.get(sid)
  1500. if event:
  1501. event.set()
  1502. try:
  1503. proc.kill()
  1504. # Bounded (#2580): an unreaped SIGKILLed ffmpeg must not hang
  1505. # the periodic cleanup loop — this janitor is the safety net
  1506. # that recovers stalled streams, so it can least afford to
  1507. # block. The /proc scan above retries the kill next pass.
  1508. await asyncio.wait_for(proc.wait(), timeout=_FFMPEG_KILL_TIMEOUT)
  1509. except (ProcessLookupError, OSError):
  1510. pass
  1511. except TimeoutError:
  1512. logger.error(
  1513. "ffmpeg (pid=%d) did not exit within %.1fs of SIGKILL; abandoning wait (stream_id=%s)",
  1514. proc.pid,
  1515. _FFMPEG_KILL_TIMEOUT,
  1516. sid,
  1517. )
  1518. _active_streams.pop(sid, None)
  1519. _disconnect_events.pop(sid, None)
  1520. _stream_last_frame_times.pop(sid, None)
  1521. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1522. cleaned += 1
  1523. # 4. Clean stale chamber stream entries
  1524. dead_chamber = [sid for sid, (_reader, writer) in _active_chamber_streams.items() if writer.is_closing()]
  1525. for sid in dead_chamber:
  1526. _active_chamber_streams.pop(sid, None)
  1527. cleaned += 1
  1528. if cleaned:
  1529. logger.info("Cleaned up %d orphaned camera stream(s)", cleaned)