camera.py 68 KB

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