camera.py 61 KB

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