camera.py 76 KB

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