camera.py 52 KB

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