camera.py 77 KB

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