camera.py 78 KB

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